Relationshipfields ForeignKey, ManyToManyField, and OneToOneField define multiple-to-one, multiple-to-many, and one-to-one Relationship field (Relationship fields) in the Model respectively)
ForeignKey, ManyToManyField, and OneToOneField define multiple-to-one, multiple-to-many, one-to-one relationships in the Model respectively.
For example, a book is published by a publishing house, and a publishing house can publish many books. A book is written by multiple authors. a single author can write many books.
Class Author (models. Model ):
Name = models. CharField (max_length = 20)
Class Publisher (models. Model ):
Name = models. CharField (max_length = 20)
Class Book (models. Model ):
Name = models. CharField (max_length = 20)
Pub = models. ForeignKey (Publisher)
Authors = models. ManyToManyField (Author)
1. associate a Model that has not been defined
If you want to associate with an undefined model, use the model name instead of the model object.
In this example, if Publisher and Author are defined after the Book, they must be written in the following form:
Class Book (models. Model ):
Name = models. CharField (max_length = 20)
Pub = models. ForeignKey ('Her her ')
Authors = models. ManyToManyField ('author ')
2. associate Model with itself
The Model can have many-to-one relationships with itself.
Class People (models. Model ):
Name = models. CharField (max_length = 20)
Leader = models. ForeignKey ('self ', blank = True, null = True)
The Model can also have many-to-many relationships with itself.
Class Person (models. Model ):
Friends = models. ManyToManyField ("self ")
By default, this association is symmetric. if Person1 is a friend of Person2, then Person2 is also a friend of person1.
P1 = Person ()
P1.save ()
P2 = Person ()
P2.save ()
P3 = Person ()
P3.save ()
P1.friends. add (p2, p3)
In the above case, you need to find a friend of p3 and use p3.friends. all () instead of p3.person _ set. all ().
If you want to cancel this symmetric relationship, set inclurical to False.
Class Person2 (models. Model ):
Friends = (models. ManyToManyField ("self", metrics rical = False)
In this way, p3.person _ set. all () is required for querying p3 friends.
3. reverse name related_name
Reverse name, used to point from the joined field to the joined field.
Note: When you define an abstract model (abstract models), you must explicitly specify the reverse name. some special syntaxes (some special syntax) are only available after you do so) can be used normally.
Class Book (models. Model ):
Name = models. CharField (max_length = 20)
Pub = models. ForeignKey (Publisher, related_name = 'pub ')
Authors = models. ManyToManyField (Author, related_name = 'author ')
In this way, you can use publisher1.pub. all () or author1.author. all () to query books in reverse mode using Publisher or Author ().
If you do not want to set a reverse relationship, set related_name to '+' or end with '+.
User = models. ForeignKey (User, related_name = '+ ')
If multiple manytomanyfields point to the same Model, you cannot find out which ManyToManyField is used in reverse query of FOO_set. you can disable the reverse relationship:
Users = models. ManyToManyField (User, related_name = 'U + ')
Referents = models. ManyToManyField (User, related_name = 'ref + ')
4. Database RePResentation)
Many-to-one: Django uses the ForeignKey field name + "_ id" as the column name in the database. In the preceding example, the table corresponding to the BOOK model has a publisher_id column.
You can explicitly specify db_column to change the column name of this field. However, you do not need to change the column name of the database unless you want to customize the SQL statement.
Many-to-many: Django creates an intermediate table to represent the ManyToManyField relationship. By default, the name of the intermediate table is composed of two relational tables.
Because some databases have limits on the table name length, the name of the intermediate table is automatically limited to 64 characters and contains a non-repeated hash string. This
It means that you may see a table name like book_authors_9cdf4. You can use the db_table option to manually specify the name of the intermediate table.
However, if you want to manually specify an intermediate table, you can use the through option to specify the model and use another model to manage the many-to-many relationship. This model is the model corresponding to the intermediate table:
Class Person (models. Model ):
Name = models. CharField (max_length = 128)
Def _ unicode _ (self ):
Return self. name
Class Group (models. Model ):
Name = models. CharField (max_length = 128)
Members = models. ManyToManyField (Person, through = 'membership ')
Def _ unicode _ (self ):
Return self. name
Class Group (models. Model ):
Name = models. CharField (max_length = 128)
Members = models. ManyToManyField (Person, through = 'membership ')
Def _ unicode _ (self ):
Return self. name
Class Membership (models. Model ):
Person = models. ForeignKey (Person)
Group = models. ForeignKey (Group)
Date_joined = models. DateField ()
Invite_reason = models. CharField (max_length = 64)
In this way, you can record when a person is added to the group.
To establish the relationship between Person and Group, you cannot use add, create, or remove. Instead, you must use Membership.
>>> Ringo = Person. objects. create (name = "Ringo Starr ")
>>> Paul = Person. objects. create (name = "Paul McCartney ")
>>> Beatles = Group. objects. create (name = "The Beatles ")
>>> M1 = Membership (person = ringo, group = beatles,
... Date_joined = date (1962, 8, 16 ),
... Invite_reason = "Needed a new drummer .")
>>> M1.save ()
Clear () can still be used
>>> Beatles. members. clear ()
When many-to-many relationships are associated with itself, the ForeignKey of the intermediate table can point to the same Model. However, they must be regarded as both sides of ManyToManyField rather than symmetric. Therefore, you must set limit rical to False.
5. other parameters (Arguments)
5.1 ForeignKey accepts the following optional parameters that define how the link runs.
ForeignKey. limit_choices_to
It is a dictionary containing filtering conditions and corresponding values, used to filter associated objects in the Django management background. For example, use the datetime module of Python to filter out the correlated objects that do not meet the filtering conditions:
Limit_choices_to = {'pub _ date _ lte ': datetime. date. today}
Only associated objects of pub_date before the current date can be selected.
You can also use the Q object instead of the dictionary to implement more complex filtering. When limit_choices_to is a Q object, it is unavailable if you place the key field in raw_id_fields of ModelAdmin.
ForeignKey. to_field
Specifies the field in the associated object and the current link. By default, to_field points to the primary key of the associated object.
ForeignKey. on_delete
When the ForeignKey associated with a model object is deleted, this object will also be deleted in Cascade mode by default.
User = models. ForeignKey (User, blank = True, null = True, on_delete = models. CASCADE)
CASCADE: default value. The model object and the ForeignKey associated object will be deleted.
SET_NULL: Set the ForeignKey field of the model object to null. Of course, you must set null to True.
SET_DEFAULT: Set the ForeignKey field of the model object to the default value.
Protect: delete the ForeignKey associated pair
A ProtectedError will be generated, so that the ForeignKey associated object will not be deleted.
SET (): SET the ForeignKey field of the model object to the value passed to SET.
Def get_sentinel_user ():
Return User. objects. get_or_create (username = 'deleted') [0]
Class MyModel (models. Model ):
User = models. ForeignKey (User, on_delete = models. SET (get_sentinel_user ))
DO_NOTHING: do nothing.
5.2 ManyToManyField accepts the following optional parameters that define how the link runs.
ManyToManyField. limit_choices_to
Same as ForeignKey. limit_choices_to.
Limit_choices_to does not work for the ManyToManyField specified by the through parameter.
ManyToManyField. Semantic rical
It works only when multiple-to-multiple links are defined recursively.
ManyToManyField. through
Manually specify an intermediate table
ManyToManyField. db_table
Specifies the name of the table in which many-to-many relationship data is stored in the database. If this option is not provided, Django generates a new table name based on the names of the two relational tables as the name of the intermediate table.
6. OneToOneField
Class OneToOneField (othermodel [, parent_link = False, ** options])
Defines a one-to-one relationship. In general, it is very similar to the ForeignKey that declares unique = True. The difference is that when we use reverse Association, we get not a list of objects, but a separate object.
This field is useful when a model is extended from another model. for example, Multi-tableinheritance) it is implemented by adding a one-to-one association to the parent model in the child model.
This field must be assigned a parameter: the associated model class. The work method is the same as ForeignKey, and the recursive and lazy connections are the same.
In addition, OneToOneField accepts the acceptable ForeignKey parameter. only one parameter is proprietary to OnetoOneField: OneToOneField. parent_link
If this parameter is set to True, it applies to the child model that inherits from a parent model. (the parent model must exist because it cannot be inherited later ), this field becomes a reference (or link) pointing to the parent class instance ),
Instead of extending the parent class and inheriting the parent class attributes like other OneToOneField.
From django. db import models, transaction, IntegrityError
Class Place (models. Model ):
Name = models. CharField (max_length = 50)
Address = models. CharField (max_length = 80)
Def _ unicode _ (self ):
Return u "% s the place" % self. name
Class Restaurant (models. Model ):
Place = models. OneToOneField (Place, primary_key = True)
Serves_hot_dogs = models. BooleanField ()
Serves_pizza = models. BooleanField ()
Def _ unicode _ (self ):
Return u "% s the restaurant" % self. place. name
Class Waiter (models. Model ):
Restaurant = models. ForeignKey (Restaurant)
Name = models. CharField (max_length = 50)
Def _ unicode _ (self ):
Return u "% s the waiter at % s" % (self. name, self. restaurant)
When using reverse association, we get not a list of objects, but a separate object:
>>> P1 = Place (name = 'deston Dogs ', address = '2017 W. Fullerton ')
>>> P1.save ()
>>> R = Restaurant (place = p1, serves_hot_dogs = True, serves_pizza = False)
>>> R. save ()
>>> P1.restaurant
>>> Place. objects. get (restaurant _ place _ name _ startswith = "Demon ")
>>> Waiter. objects. filter (restaurant _ place _ name _ startswith = "Demon ")
The above is the content in the Django document-Model. For more articles, please follow the PHP Chinese website (www.php1.cn )!