16. Table Relations

 

Many

  1. Scenario: for example, the relationship between the article and the author. Only a paper written by an author but an author can write articles. The relationship between the author and the article is typical of many-relationship.
  2. Ways: one to many or many to one, is through ForeignKeyto achieve. Or in the article and the author's case to explain.
class User(models.Model):
    username = models.CharField(max_length=20)
    password = models.CharField(max_length=100)

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    author = models.ForeignKey("User",on_delete=models.CASCADE)

Then later at a Articlespecified object author, you can use the following code to complete:

article = Article(title='abc',content='123')
author = User(username='zhiliao',password='111111')
# 要先保存到数据库中
author.save()
article.author = author
article.save()

And later if you want to get all the articles under a user, it can article_setbe achieved. Sample code is as follows:

user = User.objects.first()
# 获取第一个用户写的所有文章
articles = user.article_set.all()
for article in articles:
    print(article)

And if you want to add articles to a category. You can use it in the way:

category = Category.objects.first()

article = Article(title='bbb',content='vvv')
article.author = FrontUser.objects.first()

category.article_set.add(article,bulk=False)


Use bulk=False, then Django will automatically save the article, without the need to first save the article before you add to the category.
Or is another solution is added to category.article_setbefore, the first articlesaved to the database. But if article.categorynot empty, then produce a cycle of death, there is no article categorycan not be saved, and will add to the article cateogry.artile_set, the article before they need is already stored in the database.
* If the above is the kind of demand, it is recommended to use bulk=Falsesolutions.

One to One

  1. In Django by one models.OnetToOneFieldto achieve. This OneToOneFieldfact is essentially a foreign key, but this has a foreign key 唯一约束(unique key)to achieve one.
  2. If you want to reference later reversed, so is access to the lowercase name of the model by reference to the conversion. For example, the following model:
    class FrontUser(models.Model):
        username = models.CharField(max_length=200)
    
    class UserExtension(models.Model):
        school = models.CharField(max_length=100)
        user = models.OneToOneField("FrontUser",on_delete=models.CASCADE)
    
    # 通过userextension来访问UserExtension对象
    user = FrontUser.objects.first()
    print(user.userextension)
    

    UserExtensionObjects can useraccess to the corresponding user object. And FrontUserthe object may be used userextensionto access the corresponding UserExtensionobject.
    If you do not want to use Django's default reference property name. You can OneToOneFieldadd one related_nameparameter. Sample code is as follows:
    class FrontUser(models.Model):
        username = models.CharField(max_length=200)
    
    class UserExtension(models.Model):
        school = models.CharField(max_length=100)
        user = models.OneToOneField("FrontUser",on_delete=models.CASCADE,related_name='extension')
    
    # 通过extension来访问到UserExtension对象
    user = FrontUser.objects.first()
    print(user.extension)
    

    Then later on FrontUserthe object can, through extensionaccess to the corresponding property of UserExtensionthe object.

Many to many

  1. Scenario: for example, the relationship between articles and labels. An article can have several labels, a label can be referenced by multiple articles. Therefore, the relationship between the label and the article is typical of many relationship.

  2. Implementation: Djangoto provide for such a special realization of many to many Field. It is called ManyToManyField. Or take the article and label an example to explain. Sample code is as follows:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    tags = models.ManyToManyField("Tag",related_name="articles")

class Tag(models.Model):
    name = models.CharField(max_length=50)

At the database level, in fact, Djangois the establishment of an intermediate table for that many to many relationship. This intermediate table defines how two foreign keys, references to article, and tagthe primary key of the two tables.

Guess you like

Origin www.cnblogs.com/ys-python/p/11266191.html