django之多對多關係,django之多對關係

來源:互聯網
上載者:User

django之多對多關係,django之多對關係

django 1.7


定義多對多關係,使用 ManyToManyFiled。

本例中,文章Article可以在多個出版物Publication上發表,而出版物可以有多個文章對象。


from django.db import modelsclass Publication(models.Model):    title = models.CharField(max_length=30)        def __str__(self):        return self.title        class Meta:        ordering = ('title',)class Article(models.Model):    headline = models.CharField(max_length=100)    publications = models.ManyToManyField(Publication)    def __str__(self):        return self.headline    class Meta:        ordering = ('headline',)



下面是使用Python API執行例子的操作。注意,若你為多對多關係使用了中間體模型,有些關係管理器的方法不能使用,因此這些例子中某些在這種模型下不能工作。

建立幾個出版物:


>>> p1 = Publication(title='The Python Journal')

>>> p1.save()

>>> p2 = Publication(title='Science News')

>>> p2.save()

>>> p3 = Publication(title='Science wekkly')


建立文章:

>>> a1 = Article(headline='Django lets you build web apps easily')

在儲存它以前,不能與一個Publication關聯。


>>> a1.publications.add(p1)

...

ValueError:  'Article' instance needs to have a primary key value before a many-to-many relationship can be used.


儲存

>>> a1.save()

把Article關聯到Publication:

>>> a1.publications.add(p1)


建立另一個Article,設定它在兩個Publications中出現:

>>> a2 = Article(headline='NASA uses Python')

>>> a2.save()

>>> a2.publications.add(p1, p2)

>>> a2.publications.add(p3)

第2次添加也是正確的:


>>> a2.publications.add(p3)


添加一個錯誤類型的對象會產生一個 TypeError:

>>> a2.publictaions.add(a1)

Traceback (most recent call last):

...

TypeError: 'Publication' instance excepted


使用create()一步建立Publications並把它添加到一個文章中:

>>> new_publication = a2.publications.create(title='Highlights for Children')


Article對象可以訪問它們關聯的Publication對象:

>>> a1.publications.all()

[<Publication: HIghlights for Children>, ...]


>>> a2.publications.all()

[<Publication: Highlights for Children>, <Publication: Science News>, ... ]


Publication 對象可以訪問它們關聯的Article對象:

>>> p2.article_set.all()

[<Article: NASA uses Python>]

>>> p1.article_set.all()

[<Article: Django lets you build Web app easyily>, <Article: NASA uses Python>]

>>> Publication.objects.get(id=4).article_set.all()

[<Article: NASA uses Python>]


可以使用跨關係查詢來獲得多對多關係查詢:


>>> Article.objects.filter(publications__id=1)

[<Article: Django lets you build Web app easyily>, <Article: NASA uses Python>]


>>> Article.objects.filter(publications__pk=1)

[<Article: Django lets you build Web app easyily>, <Article: NASA uses Python>]


>>> Article.objects.filter(publications=1):

[<Article: Django lets you build Web app easyily>, <Article: NASA uses Python>]


>>> Article.objects.filter(publications=p1)

[<Article: Django lets you build Web app easyily>, <Article: NASA uses Python>]


>>> Article.objects.filter(publications__title__startwith='Science')

[<Article: NASA uses Python>, <Article: NASA uses Python>]


>>> Article.objects.filter(publications__title__startwith='Science').distinct()

[<Article: NASA uses Python>]


count()函數也使用distinct():

>>> Article.objects.filter(publications__title__startwith='Science').count()

2

>>> Article.objects.filter(publications__title__startwith='Science').distinct().count()

1


>>> Article.objects.filter(publications__in=[1,2]).distinct()

[<Article: Django lets you build Web app easyily>, <Article: NASA uses Python>]

>>> Article.objects.filter(publications__in=[p1,p2]).distinct()

[<Article: Django lets you build Web app easyily>, <Article: NASA uses Python>]


反向m2m查詢也被支援(如,從不含ManyToManyField欄位的表開始):

>>> Publication.objects.filter(id=1)

[<Publication: The Python Journal>]

>>> Publication.objects.filter(pk=1)

[<Publication: The Python Journal>]

>>> Publication.objects.filter(article__headline__startwith='NASA')

[<Publication: Highlights for Children>, <Publication: Science News>, ... ]

>>> Publication.objects.filter(article__id=1)

[<Publication: The Python Journal>]

>>> Publication.objects.filter(article__pk=1)

[<Publication: The Python Journal>]

>>> Publication.objects.filter(article=1)

[<Publication: The Python Journal>]

>>> Publication.objects.filter(article=a1)

[<Publication: The Python Journal>]

Publication.objects.filter(article__in=[1,2]).distinct()

[<Publication: Highlights for Children>, <Publication: Science News>, ... ]

>>> Publication.objects.filter(article__in=[a1,a2]).distinct()

[<Publication: Highlights for Children>, <Publication: Science News>, ... ]


排除一個關聯項目會按預期工作(儘管使用的SQL有一點複雜):

>>> Article.objects.exclude(publications=p2)

[<Article: Django lets you build Web apps easily>]


如果我們刪除Publication,它的Article將不能訪問它:

>>> p1.delete()

>>> Publication.objects.all()

[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>']

>>> a1 = Article.objects.get(pk=1)

>>> a1.publications.all()

[ ]


如果我們刪除一個Article,它的Publications將不能訪問它:

>>> a2.delete()

>>>Article.objects.all()

[<Artilce: Django lets you bulid Web apps easily>]

>>> p2.article_set.all()

[ ]


通過m2m的另一端進行添加:

>>> a4 = Article(headline='NASA finds intelligent lif on Earth')

>>>a4.save()

>>>p2.article_set.add(a4)

>>> p2.article_set.all()

[<Article: NASA finds intelligent lif on Earth>]

>>> a4.publications.all()

[<Publication: Science News>]


通過另一端使用關鍵字添加:

>>> new_article =  p2.article_set.create(headline='Oxygen-free diet works wonders')

>>> p2.article_set.all()

[<Article: NASA finds intelligent lif on Earth>, <Article: Oxygen-free diet works wonders> ]

>>> a5 = p2.article_set.all()[1]

>>> a5.publications.all()

[<Publication: Science News> ]


從1個Article移除Publication:

>>> a4.publications.remove(p2)

>>> p2.article_set.all()

[<Article: Oxygen-free diet works wonders>]

>>> a4.publications.all()

[ ]


而從另一端:


>>> p2.article_set.remove(a5)

>>>p2.article_set.all()

[ ]

>>> a5.publications.all()

[ ]


可以賦值關係集。賦值操作清除任何存在的集合成員:

>>> a4.publications.all()

[<Publication: Science News>]

>>> a4.publications = [p3]

>>> a4.publications.all()

[<Publication: Science Weekly>]


關係集可以清除:

>>> p2.article_set.clear()

>>> p2.article_set.all()

[ ]


也可以從另一端做清除:

>>> p2.article_set.add(a4, a5)

>>> p2.article_set.all()

[<Article: NASA finds intelligent lif on Earth>, <Article: Oxygen-free diet works wonders> ]

>>> a4.publications.clear()

>>> a4.publications.all()

[ ]

>>> p2.article_set.all()

[<Article: Oxygen-free diet works wonders> ]


重新建立我們刪除的Article和Publications:

>>> p1 = Publication(title='The Python Journal')

>>> p1.save()

>>> a2 = Article(headline='NASA uses Python')

>>> a2.save()

>>> a2.publications.add(p1, p2, p3)


大量刪除一些Publications - 引用刪除的publications也被刪除:

>>> Publication.objects.filter(title__startwith='Science').delete()

>>> Publication.objects.all()

[<Publication: Highlights for Children>, <Publication: The Python Journal>]

>>> Article.objects.all()

[<Article: Django lets you build Web apps easily>, .... ]

>>> a2.publications.all()

[<Publication: The Python Journal>]


大量刪除一些article - 引用刪除的對象也被刪除:

>>> q = Article.objects.filter(headline__startwith='Django')

>>> print(q)

[<Article: Django lets you build Web apps easily>]

>>> q.delete()


在delete()調用後,QeruySet緩衝需要清除,而且音樂的對象也會刪掉:

>>> print(q)

[ ]

>>> p1.article_set.all()

[<Article: NASA uses Python>]


調用clear()的替代方法是賦值空集:

>>> p1.article_set = []

>>> p1.article_set.all()


>>> a2.publications = [p1, new_publication]

>>> a2.publications.all()

[<Publication: Highlights for Children>, <Publication: The Python Journal>]

>>> a2.publications = [ ]

>>> a2.publications.all()

[ ]




相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.