Django的資料模型訪問多對多索引值的方法

來源:互聯網
上載者:User
這裡先來借用一個書本(book)的資料模型作為例子:

from django.db import modelsclass Publisher(models.Model):  name = models.CharField(max_length=30)  address = models.CharField(max_length=50)  city = models.CharField(max_length=60)  state_province = models.CharField(max_length=30)  country = models.CharField(max_length=50)  website = models.URLField()  def __unicode__(self):    return self.nameclass Author(models.Model):  first_name = models.CharField(max_length=30)  last_name = models.CharField(max_length=40)  email = models.EmailField()  def __unicode__(self):    return u'%s %s' % (self.first_name, self.last_name)class Book(models.Model):  title = models.CharField(max_length=100)  authors = models.ManyToManyField(Author)  publisher = models.ForeignKey(Publisher)  publication_date = models.DateField()  def __unicode__(self):    return self.title

訪問多對多值(Many-to-Many Values)

多對多和外鍵工作方式相同,只不過我們處理的是QuerySet而不是模型執行個體。 例如,這裡是如何查看書籍的作者:

>>> b = Book.objects.get(id=50)>>> b.authors.all()[, ]>>> b.authors.filter(first_name='Adrian')[]>>> b.authors.filter(first_name='Adam')[]

反向查詢也可以。 要查看一個作者的所有書籍,使用author.book_set ,就如這樣:

>>> a = Author.objects.get(first_name='Adrian', last_name='Holovaty')>>> a.book_set.all()[, ]

這裡,就像使用 ForeignKey欄位一樣,屬性名稱book_set是在資料模型(model)名後追加_set。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.