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: “<Article: 坏蛋是怎样炼成的>” 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()
<QuerySet [<Publication: 人民出版社>]>
a2.publications.all()
<QuerySet [<Publication: 人民出版社>, <Publication: 光明出版社>, <Publication: 机械出版社>]>

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

p1.article_set.all()
<QuerySet [<Article: 三国演义>, <Article: 坏蛋是怎样炼成的>]>
p2.article_set.all()
<QuerySet [<Article: 三国演义>]>
Publication.objects.get(id=1).article_set.all()
<QuerySet [<Article: 三国演义>, <Article: 坏蛋是怎样炼成的>]>

多对多关系跨关系查询

Article.objects.filter(publications__id=1)
<QuerySet [<Article: 三国演义>, <Article: 坏蛋是怎样炼成的>]>
Article.objects.filter(publications__pk=1)
<QuerySet [<Article: 三国演义>, <Article: 坏蛋是怎样炼成的>]>
Article.objects.filter(publications=1)
<QuerySet [<Article: 三国演义>, <Article: 坏蛋是怎样炼成的>]>
Article.objects.filter(publications=p1)
<QuerySet [<Article: 三国演义>, <Article: 坏蛋是怎样炼成的>]>
Article.objects.filter(publications__title__startswith='人民')
<QuerySet [<Article: 三国演义>, <Article: 坏蛋是怎样炼成的>]>
Article.objects.filter(publications__title__startswith='人民').distinct() #去重
Publication.objects.filter(id=1)
<QuerySet [<Publication: 人民出版社>]>
Publication.objects.filter(pk=1)
<QuerySet [<Publication: 人民出版社>]>
Publication.objects.filter(article__headline__startswith='三国')
<QuerySet [<Publication: 人民出版社>, <Publication: 光明出版社>, <Publication: 机械出版社>]>


Publication.objects.filter(article__id=1)
<QuerySet [<Publication: 人民出版社>]>
Publication.objects.filter(article__pk=1)
<QuerySet [<Publication: 人民出版社>]>
Publication.objects.filter(article=1)
<QuerySet [<Publication: 人民出版社>]>
Publication.objects.filter(article=a1)
<QuerySet [<Publication: 人民出版社>]>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值