This article is an example of Django framework multi-table query. Shared for your reference, as follows:
Multi-table querying is one of the most important features of the model layer, Django provides a unique solution based on associative fields.
ForeignKey
Example of a model from the official Django documentation.
from import models class Blog(): name = (max_length=100) tagline = () class Author(): name = (max_length=50) email = () class Entry(): blog = (Blog) authors = (Author) headline = (max_length=255) body_text = () pub_date = () mod_date = () n_comments = () n_pingbacks = () rating = ()
class ForeignKey
The ForeignKey field accepts a Model class as a parameter, of exactly the same type as the field being referenced.
blog = (Blog)
ForeignKey.to_field
The name of the field of the associated object to which the association is linked. By default, Django uses the primary key of the associated object.
blog = (Blog, to_field=)
ForeignKey.db_constraint
The main function of the Django Model's ForeignKey field is to maintain a one-to-many relationship, in order to perform associative queries.
Only indb_constraint=True
The Django model creates a foreign key constraint on the database when the value is False.
default (setting)db_constraint=True
.
ForeignKey.related_name
This name is used to make the associated object look back to the source object.
If you don't want Django to create a reverse association, set related_name to '+' or end with '+'.
ForeignKey.related_query_name
in order toForeignKey.related_name
As a default, see the documentation for a detailed description of both functions.
Querying with ForeignKey
forward lookup
If relational model A contains an association field associated with model B, an instance of model A can access an instance of model B associated with it through the association field:.
>>> e = (id=2) >>> # Returns the related Blog object.
modificationsand call the save method to save to the database
>>> = some_blog >>> ()
If the ForeignKey field hasnull=True
setting (i.e., it allows NULL values), None can be assigned to remove the corresponding correlation
>>> e = (id=2) >>> = None >>> () # "UPDATE blog_entry SET blog_id = NULL ...;"
Django provides a way to use the double underscore__
The query syntax of the
>>> (blog__name='Beatles Blog')
reverse inquiry
The indexed relational model has access to all instances of the model that refer to it, e.g. as a foreign key to Blog, by defaultBlog.entry_set
It is a query set which contains all the examples of Entry with reference to Blog, you can use the query set API to retrieve the corresponding instances.
>>>b = (id=1) >>>b.entry_set.all()
The related_name and related_query_name set the name of this query set.
ManyToManyField
Example from the Django website:
from import models class Person(): name = (max_length=50) class Group(): name = (max_length=128) members = (Person, through='Membership', through_fields=('group', 'person')) class Membership(): group = (Group) person = (Person) inviter = (Person, related_name="membership_invites") invite_reason = (max_length=64)
class ManyToManyField
Django automatically creates a table to manage many-to-many relationships, but to specify the table manually you need to use the through keyword parameter.
ManyToManyField.through_fields
In the example above, Membership has two foreign keys to Person (person and inviter), which makes the association ambiguous and leaves Django wondering which one to use.
In this case, you must explicitly specify which foreign keys Django should use using through_fields
through_fields receives a binary group ('field1', 'field2'), where field1 is the name of the foreign key pointing to the model that defines the ManyToManyField field (in this case, group), and field2 is the name of the foreign key pointing to the target model (in this case, person).
ManyToManyField.db_table
By default, the name of the associated table is generated using the name of the many-to-many field and the name of the model containing this table and the hash value, e.g..memberShip_person_3c1f5
To specify a table name manually, you can use thedb_table
Keyword parameter specification.
others
The following APIs are identical to the API of the same name in ForeignKey.
- ManyToManyField.db_constraint
- ManyToManyField.related_name
- ManyToManyField.related_query_name
Querying with ManyToManyField
Many-to-many relationships and ForeignKey have similar APIs.
>>>e = (id=3) >>>() # Returns all members objects for this Group.
Reverse Query:
>>>a = (id=1) >>>a.group_set.all()
Similarly related_name sets the name of the reverse query set.
Adding and deleting associations
Because ManyToManyField automatically maintains the association table, it is not easy for programmers to access it directly. ManyToManyField provides an API for adding and removing associations (i.e., records in through tables).
Use a model that automatically maintains through tables as an example:
class User(): user_id = (primary_key=True) class Flight(): flight_id = (primary_key=True) reserve = (User, related_name='flight_reserve')
First get the Flight and User instances to be associated:
flights = (flight_id=flight_id) if () != 0: flight = flights[0] users = (id=user_id) if () != 0: user = users[0]
The add association operation is performed through the Flight instance that has the associated field:
(user) ()
The delete operation is similar to this:
(user) ()
I hope that what I have said in this article will help you in designing Python programs based on Django framework.