Can I create a related Django field between two models with a shared foreign key value? - django

I have two models:
class Foo(Model):
special_id = IntegerField(primary_key=True)
class FooDetail(Model):
special_id = IntegerField(primary_key=True)
special_id comes from an outside source -- it's a foreign key into another database. Yes, Foo and FooDetail should be combined into a single model -- but assuming I can't -- can I create a related field between the two models such that I can use it in queries (like in values or select_related)?
I could add a ForeignKey('FooDetail') in Foo, but I'd be essentially storing the special_id twice.

If you want to use the ORM's features for related models, you should create a relationship (one-to-one in this case) between the two models. In one of the models you can (and should) then omit the special_id reference.
You can use the foreign key as a primary key in FooDetail, and if you keep special_id as a primary key in Foo, you'll be saving exactly the same type and amount of columns and data as in your example (namely one column in each that contains the relevant special_id).
What you get though is the benefit of a relationship and enforced integrity.
The only difference is that when you introduce a new special_id, you have to create Foo first to be able to point to it in FooDetail – hardly a big price to pay.
If you get a warning on setting the reference field to Foo to be the primary key then it might be that you defined it as a ForeignKey. You should define the field as a OneToOneField since you're dealing with a one-to-one relationship as noted above. The field is still technically a foreign key (= reference to the primary key of a row in another table) which is why I used this term; but it has a unique constraint that allows it to be used as a primary key.

Related

Is there a way to create a so-called multi-typed model field?

Preface
I need to have objects (Object model) with an individual set of fields (Field model). It contains name and type (see the diagram). Each connection between Object and Field stores the field's value. Datatype of value depends on the Field type property and physically the value will be stored in one of the predefined db columns (value_number, value_text, ...).
How I want it to work:
field = Field.objects.get(pk=1)
sought_for = Object.fields.filter(field=field, value='test')
Is there a way to create such a field that can be put to QuerySet just as simple as in the example but it actually, depending on the field's type, uses different db column or even columns as I suppose that in the future there will types that involve more than one column to store its value.
P.S. I tried some EAV applications but they seemed to be too complicated for my case.
The diagram:
Field model, it stores name and type of fields
FieldValue, the model the values for the fields are stored.
UPD: Eventually I came to a thought that the very approach to use Postgres (or any relational database) is not the best choice. I got this implemented easily in MongoDB.

How do I express a Django ManyToMany relationship?

I'm hitting a wall here and I know this is a simple question, but I was unable to find it here.
In an ER diagram, what would the relationship be between two objects that have a ManyToMany relationship, in terms of the intermediary table?
Example:
item ---- item_facts ---- fact
I feel like it should be one to one but I'm not completely sure.
user --many2many-- group
user 1----n user_group n---1 group
In django documentation it states that
A many-to-many relationship. Requires a positional argument: the class to which the model is related. This works exactly the same as it does for ForeignKey, including all the options regarding recursive and lazy relationships.
Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. By default, this table name is generated using the name of the many-to-many field and the model that contains it. Since some databases don't support table names above a certain length, these table names will be automatically truncated to 64 characters and a uniqueness hash will be used. This means you might see table names like author_books_9cdf4; this is perfectly normal. You can manually provide the name of the join table using the db_table option.
And ForeignKey definition is like:
A many-to-one relationship. Requires a positional argument: the class to which the model is related.
So,ManyToMany relations created by django are creating intermedıary tables that are 1 to N.
Not sure what the question is here. You say that the two objects have a many-to-many relationship.
If two objects (entitied, tables) have a many-to-many relationship, whether you include the intermediate table in the diagram or not, is irrelevant. They still have a many-to-many relationship.

One-to-many relation ship between 3 entities in Doctrine 2

I have three entities: User, Office and PhoneNumber. The user has many phone numbers, and the office has many phone numbers too.
The problem is how to represent these entities relations in Doctrine 2.
At first I tried to use bi-directional one-to-many associations
(User -> has many -> PhoneNumbers) (Office -> has many ->
PhoneNumbers), the PhoneNumber has two mapping fields, one for User
and anotherone for Office. This solution doesn't work since one of
the mapping foreign keys couldn't be null.
My second approach was to use two entities and one superclass for PhoneNumber. The PhoneNumber superclass has defined all common fields except the mapping field. Entities UserPhoneNumber and
OfficePhoneNumber extended the PhoneNumber entity and specified the
different mapping field and different table. (one table for OfficePhoneNumbers, anotherone for UserPhoneNumbers)
This solution actually works, but it is quite ugly to have 3
classes to represent one simple entity.
My third approach is to use uni-directional one-to-many mapping. This will eliminate the need of mapping field for the PhoneNumber entity. The problem is that when I use cascade remove for the many-to-many field, it violates the integrity constraint when deleting records.
When I omit the cascade remove option, after removing User or Office, the PhoneNumber remains in the Database (but the record in mapping table is removed).
What is the best way to handle this type of association?
Thanks
I finally solve the problem connected with (probably the nicest) solution 1). The problem was in misunderstanding of mappedBy attribute which should specify the entity field, not the database field.

Primary key and unique key in django

I had a custom primary key that need to be set up on a particular data in a model.
This was not enough, as an attempt to insert a duplicate number succeeded. So now when i replace primary_key=True to unique=True it works properly and rejects duplicate numbers!!. But according this document (which uses fields).
primary_key=True implies null=False
and unique=True.
Which makes me confused as in why does
it accept the value in the first place
with having an inbuilt unique=True ?
Thank you.
Updated statement:
personName = models.CharField(primary_key=True,max_length=20)
Use an AutoField with primary_key instead.
Edit:
If you don't use an AutoField, you'll have to manually calculate/set the value for the primary key field. This is rather cumbersome. Is there a reason you need ReportNumber to the primary key? You could still have a unique report number on which you can query for reports, as well as an auto-incrementing integer primary key.
Edit 2:
When you say duplicate primary key values are allowed, you indicate that what's happening is that an existing record with the same primary key is updated -- there aren't actually two objects with the same primary key in the database (which can't happen). The issue is in the way Django's ORM layer chooses to do an UPDATE (modify an existing DB record) vs. an INSERT INTO (create a new DB record). Check out this line from django.db.models.base.Model.save_base():
if (force_update or (not force_insert and
manager.using(using).filter(pk=pk_val).exists())):
# It does already exist, so do an UPDATE.
Particularly, this snippet of code:
manager.using(using).filter(pk=pk_val).exists()
This says: "If a record with the same primary key as this Model exists in the database, then do an update." So if you re-use a primary key, Django assumes you are doing an update, and thus doesn't raise an exception or error.
I think the best idea is to let Django generate a primary key for you, and then have a separate field (CharField or whatever) that has the unique constraint.

many-to-many relation with extra fields - how to circumvent uniqueness

I have the following task.
Having three models Project, User and PurchaseOrder. I want to be able to create a membership for a User in a Project. A User can be a member in arbitrary Projects. This can be solved with a
ManyToManyField.
Additionally a membership should reference to a PurchaseOrder, since I want to assign the working hours to specific PurchaseOrders.
I think this could be solved by using a through-table for the ManyToManyField, and defining a ForeignKey to the PurchaseOrder model. Thus I would have for each membership a reference to a PurchaseOrder.
In reality a membership for a project will stay active, whereas after the money is spend for a PurchaseOrder, a new PurchaseOrder has to be assigned to the membership. This would also be easy by just updating the ForeignKey to a new PurchaseOrder.
But now my question:
I want to keep the old Project-membership-PurchaseOrder-Relation (data row in the membership table, for history tracking), set it to disabled and add a new Project-membership-PurchaseOrder-Relation, which would have the same ForeignKey to User and Project, but a different to the PurchaseOrder, and a flag set to enabled.
Is this a valid approach, will this work, will it be possible to circumvent uniqueness (or is there no uniqueness for the ManyToManyField by definition), or do you have a better idea how to do this?
When I read through this I can't figure out why even bother with the Many-to-Many relation for the Member > PurchaseOrder.
I would make it a One-to-Many relation for Member > PurchaseOrder and a Many-to-Many relation Member > Project, as the Membership appears to be the primarykey for it all.
In that way, you don't have to update any keys. Then I would create a fourth Model, having a Many-to-Many relation keeping track of the purchases. Adding the Membership prim. key and the PurchaseOrder prim.key.