ManyToManyField

class User(models.Model):
    username = models.CharField(max_length=108)

class Tag(models.Model):
    title = models.CharField(max_length=108)

    # 使用ManyToManyField只能在第三张表中创建三列数据
    m = models.ManyToManyField(to='User')

联合唯一

	from django.db import models
	from datetime import datetime
	
	
	# Create your models here.
	
	class User(models.Model):
	    username = models.CharField(max_length=108)
	
	    def __str__(self):
	        return self.username

	
	class Tag(models.Model):
	    title = models.CharField(max_length=108)
	
	    def __str__(self):
	        return self.title


	class UserToTag(models.Model):
	    u = models.ForeignKey(to='User', on_delete=models.CASCADE)
	    t = models.ForeignKey(to='Tag', on_delete=models.CASCADE)
	    add_time = models.DateTimeField(default=datetime.now())

	    class Meta:
	        # 联合唯一
	        unique_together = [
	            ('u', 't'),
	        ]

自关联

class User(models.Model):
    username = models.CharField(max_length=108)
    d = models.ManyToManyField('User', related_name='b')  # 自关联

    def __str__(self):
        return self.username

出版社与书籍的多对多关系

一个出版社可以出版多种书籍,一本书籍也可以由多个出版社出版。

# 书籍与出版社的多对多关系
class Publication(models.Model):
    title = models.CharField(max_length=30, verbose_name='标题')

    def __str__(self):
        return self.title

    class Meta:
        ordering = ('title',)


class Article(models.Model):
    headline = models.CharField(max_length=30)
    publications = models.ManyToManyField(Publication)

    def __str__(self):
        return self.headline

    class Meta:
        ordering = ('headline',)

创建一些出版社

p1 = Publication(title='人民出版社')
p1.save()
p2 = Publication(title='机械出版社')
p2.save()
p3 = Publication(title='光明出版社')
p3.save()

创建一本书籍

Tip: 创建书籍时,需要先保存书籍,再对书籍和出版社进行关联;
否则会报错:ValueError: “” needs to have a value for field “id” before this many-to-many relationship can be used.

a1 = Article(headline='坏蛋是怎样炼成的')
a1.save()
a1.publications.add(p1)

再创建一本书籍

a2 = Article(headline='三国演义')
a2.save()
a2.publications.add(p1, p2)
a2.publications.add(p3)

通过书籍获取它们的出版社信息

a1.publications.all()
]>
a2.publications.all()
, , ]>

通过出版社信息获取它们出版的书籍

p1.article_set.all()
, ]>
p2.article_set.all()
]>
Publication.objects.get(id=1).article_set.all()
, ]>

多对多关系跨关系查询

Article.objects.filter(publications__id=1)
, ]>
Article.objects.filter(publications__pk=1)
, ]>
Article.objects.filter(publications=1)
, ]>
Article.objects.filter(publications=p1)
, ]>
Article.objects.filter(publications__title__startswith='人民')
, ]>
Article.objects.filter(publications__title__startswith='人民').distinct() #去重
Publication.objects.filter(id=1)
]>
Publication.objects.filter(pk=1)
]>
Publication.objects.filter(article__headline__startswith='三国')
, , ]>


Publication.objects.filter(article__id=1)
]>
Publication.objects.filter(article__pk=1)
]>
Publication.objects.filter(article=1)
]>
Publication.objects.filter(article=a1)
]>

你可能感兴趣的:(python)