Django foreign key reverse - multiple models - django-models

I have a Django project with a quite generic model Document, and then two different models Model1 and Model2 which both have a foreign key relationship to Document:
class Model1(models.Model):
document = models.ForeignKey(Document, ..)
class Model2(models.Model):
document = models.ForeignKey(Dcoument, ..)
now getting from a Model1/Model2 instance to the corresponding document is of course quite simple - but when I have a Documentinstance - is there a simple way to get back to the corresponding Model1or Model2 instance - without knowing which class to chase?
Right now I have embedded a CharField() in the Document class which points to the URL of the correct model instance - that solves the immediate problem, but it is not very general.

Related

Attributes of Wagtail Page Class failed to be inherited

I have below PostDetail Model defined
from wagtail.core.models import Page
class PostDetail(Page):
template = "Post_Detail.html"
body = RichTextField(blank=True)
After python manage.py migrate, when I examine the database table of PostDetail, I only see 2 columns (attributes) and did not see all those attributes (title / owner / first_published_at etc according to the source code here.) which are supposed to be inherited from Page model.
Anything I missed out or did wrong ?
Wagtail's Page model uses multi-table inheritance - the shared fields from the base class are stored in a record on the wagtailcore_page table, while the fields specific to a subclass are in a separate table with a link back to the base wagtailcore_page record.
Having all of the 'core' fields in a single table makes it possible to retrieve (for example) the child pages of a given page, without having to search in every table for every possible page type.

How to provide model configuration presets in Django

so what I am trying to achieve is the following:
I have two models A and B which have a OneToOne relationship. Instances of model A are always created before their respective model B instances. Dependent on a parameter, I want to be able to initialize an instance of model b with different initial values.
What I've come up with is to define a ProtoTypeModel and subclass it with the actual Model like so:
from django.db import models
#other imports
class PrototypeB(models.Model):
#define all fields
class B(PrototypeB):
pass
By using dict = PrototypeB.objects.filter(**my criteria).values()[0] or a custom Serializer from Django Rest Framework, I will get a dict which I can then use to instantiate my instance of model B : B.objects.create(**dict).
Is this the proper way to do so or am I missing a huge point?
Best,
D
In case anyone stumbles upon the same question on his path, here's how I did it.
First I thought about implementing the solution I mentioned above. However, researching about multi table inheritance, I found that this is actually a non functioning one.
The multi table inheritance will create an implicit OneToOne _ptr field, which will trigger cascade deleting behavior, causing my arche type models to be deleted, when an instance of B is deleted.
I went along implementing two models PrototypeB and B which works perfectly fine.

ASP.net Web API - Example pre-existing database Fluent NHibernate and Automapper

I am working through the ASP.net Web API 2 book (Git Hub)
I am trying to use Fluent NHibernate and Automapper to connect to a database. The book uses a fresh database while my database is pre-existing and not necessarily controlled by good practices.
Before joining tables etc. I would like to just be able to get a list of people and add a new person via the API. The only catch is that I would like to return less properties of the actual table and create a new person with even less than the model used to display a new person. I am having trouble understanding the flow of the automapper.
An example table might be
<pre>Person Entity
-person_id(int)
-person_name(varchar(100))
-person_location(int)
-person_phone(varchar(10))
-person_address(varchar(30))
</pre>
The model I want to use includes a subset of the items in the actual table. For example, maybe:
<pre>Person Model
-person_id(int)
-person_name(varchar(100)
-person_location(int)</pre>
There is also a newPerson model
<pre>NewPerson Model
-Name
-location</pre>
I have an Entity with all the person properties like
public virtual int person_id {get;set;}
but I have a model with the subset properties like
public long person_id {get; set;}
In the automapping configuration file I have a class NewPersonToPersonEntityAutoMapperTypeConfigurator and I have another class PersonEntityToPersonAutoMapperTypeConfigurator
I'm confused about how automapper is working. Should the AutoMapper file NewPersonToPersonEntityAutoMapperTypeConfigurator use something like
Mapper.CreateMap<NewPerson, PersonEntity>
.ForMember(opt => opt.person_id, x => x.Ignore())
...
.ForMember(opt => opt.person_address(varchar(30)))
While
PersonEntityToPersonAutoMapperTypeConfigurator uses something like
Mapper.CreateMap<PersonEntity, PersonModel>
Can anyone show me a good example of a simple scenario like this with automapper and a pre-existing table with extra unused properties or describe what Automapper should be doing or if I am on the right track?
Daniel - I think you're on the right track. Yes, you need an AutoMapper map for each "direction"... i.e. incoming service message to the EF entity, and from the EF entity to the service return message.
Your code to ignore certain properties is fine. You just need to make sure the entity is populated appropriately for the INSERT into the database. For example, the person_id column - is that required to be set? Or is that an auto-incrementing column??
To say it another way... you can certainly use AutoMapper (and our approach in the book) against an existing database. It's still just mapping properties from one type to another type.
Feel free to send some code my way.

How does cakePHP naming convention work?

I'm relatively new to PHP. Started learning PHP, but then come across cakePHP, which is suppose to speed up development time.
After reading the documentation and blog tutorial I still don't understand the naming convention. I guess I won't know until I start to do some examples, but to get me started can someone please explain to me how cakePHP associate database tables to the controller/model layer?
The below code is an abstract from the tutorial. It is a controller method that passes the post id to the view layer. The database table is called "posts". $this->Post refers to the model class of Post, which correlates to the plural form of posts in the database.
public function view($id = null) {
$this->Post->id = $id;
$this->set('post', $this->Post->read());
}
OK I get that. Then, in the documentation it refers to the following correlation:
ReallyBigPerson and really_big_people
So it seems like the correlation actually follows the rule in English semantics. Does this mean that cakePHP has a list of singular and plural words hidden somewhere that it works from? For example can I use the below correlation without breaking the code?
This and these or Man and men or Foot and feet or Moose and moose or Goose and geese
Furthermore, if I have both singular and plural form of tables in my database, will it break the code, or will it just associate to the plural-formed table?
Just find it baffling... Why couldn't they just match the naming convention like for like with prefixes?
Inflector
CakePHP uses its Inflector class to determine the plurals of things.
Since the naming conventions dictate that model names are singular and tables names are pluralised, it uses the inflector to apply English semantics / rules to determine the plural.
If you need some help understanding the output of the Inflector, you can use the CakePHP inflector website.
Pluralisation Examples
Model name: Post
Table name: posts
Model name: User
Table name: users
Model name: Sheep
Table name: sheep
Model name: News
Table name: news
Model name: Radius
Table name: radii
Check the Inflector site to be sure.
Non-standard Table names
While CakePHP offers a standard rule set for naming and conventions, none of it is set in stone. If you want to change the name of the table used for a particular model, simply specify the table name in the model:
class Thing extends AppModel {
public $useTable = 'somethings';
}
Or, if you want a model that does not use a table:
class Post extends AppModel {
public $useTable = null;
}

app engine ndb - how to load entity by key using id?

I am trying to load an entity by key using the id it was assigned by the datastore but I don't see any api method to do this (using NDB). I thought I would be able to make a Key from an integer id and use key.get() to load the entity, but I don't see a way to make a key from just an id. I suspect I am missing something obvious here. How should I load an entity where I only know the id of it?
Another way: ndb.Key(YourModel, id).get().
YourModel.get_by_id() gets a model instance by id.
here the docs:
https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_get_by_id
don't think you can't get an entity by id without knowing the kind because instances of different Model classes can have the same id/key_name
Models in NDB don't define their key type as part of the model. This is nifty in that you can have one given model type that is accessible through multiple different kinds of keys and parents, which makes them more flexible. But it's somewhat problematic because it isn't always clear what the key represents or where it comes from.
So in cases where there's only ever one kind of key for a given model (which is almost every model), I like to create a class method for generating that key, which adds a bit of semantic clarity:
class Book(ndb.Model):
title = ndb.StringProperty()
pages = ndb.IntegerProperty()
#classmethod
def make_key(cls, isbn):
return ndb.Key(cls, isbn)
b = Book.make_key('1234-5678').get()
Sure the added code is not strictly necessary, but it adds clarity and makes my models more long-term maintainable.
You can parse the id to key string:
key = ndb.Key(YourModel, id).urlsafe().
and then:
result = YourModel.query(YourModel.key== key).get().

Resources