Hi, I’m Yan Gan, and today I’m bringing you Django4- One-to-one, One-to-many, Many-to-many relationships.

Environment: Django 2.2.1 + Python 3.6.7

Obviously, the power of relational databases lies in the relational relationships between tables. Django provides a way to define three of the most common database relationships: one-to-one, one-to-many, and many-to-many.

One to one

The typical example is one student for one ID card, one ID card for one student. Or the Dj document example, where a Place corresponds to a Restaurant. In Dj, one-to-one relationship is associated with OneToOneField. After association, the location table can query the data of the restaurant table, and the restaurant table can also query the data of the location table.

Example: docs.djangoproject.com/zh-hans/2.2…

More than a pair of

A typical example is a class with multiple students, and a student can only belong to one class. Or the Dj document example, where one Reporter can write multiple articles, and one Article belongs to only one author. In Dj, one-to-many relationships are associated using ForeignKey.

Note that the forward query is the article table to look up data from the author table and the reverse query is the author table to look up data from the article table.

Official document Demo test

#Table R -> TABLE R, table A -> table A

#Create an associatest, assuming the application is registered
$ python manage.py makemigrations associatest

#Create a new Model (consistent with official documentation)
https://docs.djangoproject.com/zh-hans/2.2/topics/db/examples/many_to_one/

#Data Migration, Hoisting + SQLmigrate +migrate1. The table name is in the form of application name_model name, for example, Associatest_reporter 2. If no primary key is specified, the system automatically adds the primary key id. 3. The foreign key name of table A is reporter_id, which is associated with the primary key ID of table R
#Add data to table R (not affected by table A)
$ python manage.py shell
>>> from associatest.models import Reporter
>>> r = Reporter(first_name='John', last_name='Smith', email='[email protected]')
>>> r.save()
>>> r2 = Reporter(first_name='Paul', last_name='Jones', email='[email protected]')
>>> r2.save()

#Add data to table A (will be affected by table R, corresponding reporter must exist)
>>> from associatest.models import Article
>>> from datetime import date
>>> a = Article(id=None, headline="test", pub_date=date(2005, 7, 27), reporter=r)
>>> a.save()


#Table R filters the data, resulting in A querySet.
>>> Reporter.objects.filter(article=1)
<QuerySet [<Reporter: John Smith>]>

>>> Reporter.objects.filter(article__headline='test')
<QuerySet [<Reporter: John Smith>]>


#Table A filters data
>>> Article.objects.filter(reporter__first_name='John')
<QuerySet [<Article: test>]>


#Table R queries table A (filter returns A queryset, get returns an object)
>>> r3 = Reporter.objects.get(first_name='John')
>>> r3.Article__set().get(headline='test').id  


#Table A queries the data of table R
>>> a.reporter.first_name
'John'
>>> a.reporter.id
1


#Field parameters-to_field: By default, reporter fields are associated with the primary key of table R, but other fields of table R can be specified through to_field, provided that the specified fields are unique. -related_name: Specifies the field to be used for reverse query. Reverse query refers to table R looking up table A. The default field is Article__set(). If you do not want a reverse lookup, assign related_name to '+'. -on_delete: specifies the behavior of a foreign key when it is deleted. -on_delete =CASCADE: specifies the default value for deleting a foreign key. -protect: Protected mode. If this option is selected, a ProtectedError error will be raised when you delete the node. -set_NULL: specifies the null mode. When a foreign key field is deleted, the field is set to null if blank = True and null = True. -set_default: set the default value. When deleting the foreign key, the foreign key field is set to the default value. Therefore, add a default value when defining the foreign key. -set (): define a value for the corresponding entity. -do_nothing: do nothing. -db_column: If you want to avoid reported_id, you can use the db_column parameter to specify the name of the column.Copy the code

Many to many

A typical example is that one teacher can teach more than one class, and one class can be taught by more than one teacher. Or in the case of Dj documents, a Publication can publish multiple articles, and an Article can be published by multiple publishers. In Dj, many-to-many relationships are associated using a ManyToManyField.

Docs.djangoproject.com/zh-hans/2.2…

OneToOneRel and OneToOneField differences:

The Django relational model exposes only three of these models. OneToOneRel, ManyToOneRel, and ManyToManyRel are classes used internally by all three.

Reference:

Django_ foreign key query and reverse query: www.jianshu.com/p/20e078a71…

Django foreign key field parameters: docs.djangoproject.com/zh-hans/2.2…