Relationships

Django also defines a set of fields that represent relations.

ForeignKey

A many-to-one relationship. Requires a positional argument: the class to which the model is related. To create a recursive relationship-an object that has a many-to-one relationship with itself-use models.ForeignKey('self').

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:

from django.db import models 
 
class Car(models.Model): 
    manufacturer = models.ForeignKey('Manufacturer') 
    # ... 
  
class Manufacturer(models.Model): 
    # ... 
    pass 

To refer to models defined in another application, you can explicitly specify a model with the full application label. For example, if the ...

Get Mastering Django: Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.