I've always been using ForeignKeys.
A one-to-one relationship is a unique relation between two entities in both directions. I.e. for an entity A there exists only one entity B and vice versa.
The documentation says:
Conceptually, this is similar to a ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.
This is most useful as the primary key of a model which "extends" another model in some way; Multi-table inheritance is implemented by adding an implicit one-to-one relation from the child model to the parent model, for example.
Related
I have a model. I want a list of models which have foreign key (or any) relation with my given model. please help.
In case you have a ForeignKey relation, then Django makes a relation in reverse as well. You thus can inspect the Options object [Django-doc]. We thus can obtain a list of fields with:
[field for field in MyModel._meta.get_fields() if field.is_relation]
you can obtain the model to which these are linked by accessing the .related_model attribute [Django-doc]:
[field.related_model for field in MyModel._meta.get_fields() if field.is_relation]
Is there a OneToManyField relationship in Django? There is a ManyToOneField relationship but that restrict you declare the relationship on the Many side.
You should recognise that Django fields represent database columns. A ForeignKey field is exactly that, a field on the model that represents a key in another model. But you can't model a "one-to-many" field in that way; what would the field on the model represent? So no, it is not possible.
Django offers Related objects for oneToMany or manyToMany relationship.
Using this object, It can create a record from the reverse direction.
(for example with XXXX_set.create(.....) or XXXX_set.get_or_create(.....))
I want to use this kind of function with an oneToOne relationship.
Is there any way to create an one to one relationship record from the reverse direction ?
for example
If class A(models.Models) and class B(models.Model) are tied by one to one relationship and I create A and save() it, than I want to create B also through A
No, there is no way of doing that because there is no queryset between class A and class B, like it was with ManyToMany or ForeignKey. You must create B directly and assign A to proper field on B.
There is something that is tripping me up with models, and I guess SQL tables in general.
Let us suppose you have these models:
class Manufacturer(models.Model):
name = models.CharField()
company_created = models.CharField()
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer)
When you create an instance of Car like say, the following
civic = Car(manufacturer='honda')
A couple questions:
When you create an instance of Car, are you also creating an instance of Manufacturer as a by-product? Or does 'honda' need to exist as an instance already. If not, is there a way to make an instance of both, in say, one form.
Can I make calls on 'civic' for things pertaining to the manufacture? For example, could I get the 'company_created' data from the civic instance? If not, why bother having the relationship in the first place?
Thanks so much in advance. I would really appreciate a thorough answer so I can understand models and relationships fully. And yes, I have read the docs.
Firstly, the thing to remember is that these classes are representations of underlying database tables. A ForeignKey field in a Django model represents a one-to-many relationship in the database, with an _id field representing the ID of another table. Those tables are themselves independent, but are linked via the FK field (and the relevant index constraint, if the database supports them).
That said, in your Car model manufacturer is a required field (because you haven't defined it as null=True). So when you create a Car, you must point it at an already existing Manufacturer - and that manufacturer must have been saved already, so that Django can populate the underlying manufacturer_id field with the ID of the related object
Because Django is aware of the foreign key relationship between the two objects, you can use them when querying. In SQL this would be done via JOINs: Django gives you a special syntax to do queries across those joins, via double underscores. So, for example, if you wanted to get all the cars made by a manufacturer created in 1990 (assuming that's what you mean by the company_created field), you would do this:
Car.objects.filter(manufacturer__company_created='1990')
Django translates this into something like":
SELECT * from car JOIN manufacturer ON car.manufacturer_id=manufacturer.id WHERE manufacturer.company_created='1990';
If you already have your "civic" instance and just want to get access to the related data, this is pure Python object access: civic.manufacturer is the related Manufacturer object, so you can simply do civic.manufacturer.company_created to get the relevant data. Again, Django translates that into the database access, but from your point of view this is simple object composition.
Note that really all this is fully explained in the tutorial, with relationships between Poll and Choice which exactly match your Manufacturer and Car models.
Yes manufacturer need to exist as an instance already.
you can create car instance like this:
manuf= Manufacturer(name='honda',company_created='Benz')
manuf.save()
civic = Car(manufacturer=manuf)
you can get the company_created data from the civic instance by:
civic.manufacturer.company_created
I want to design a Task model that can be associated to Project Models, another X model, and other Task models. The obvious choice is a foreign key, but I want any particular instance of that Task model to only be associated to only one of those model types, that is, if a Task model has a relationship with a Project model, it cannot have a relationship with another Task model, and so on. Any advice in what would be the best way to represent this? Thanks.
Have a look at Generic relation. It lets you define a foreign key on multiple models. This way your task is only linked to one of your models.
What I have done is to inherit from a base class on all my models that will be related to tasks. Task models points to that base class on the ForeignKey with unique=True, and it seems like all subclasses inherit the relationship. Thanks.