在Django的多对多关系中获得额外的字段值

时间:2014-08-28 15:24:26

标签: django django-models

在Django的多对多关系字段中,我们可以添加额外的字段,如下面的代码(来自https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany),我的问题是如何轻松获得额外的字段,是有可能不直接在中间表上查询?确切的例子是:

>>> ringo = Person.objects.create(name="Ringo Starr")
>>> paul = Person.objects.create(name="Paul McCartney")
>>> beatles = Group.objects.create(name="The Beatles")
>>> m1 = Membership(person=ringo, group=beatles,
...     date_joined=date(1962, 8, 16),
...     invite_reason="Needed a new drummer.")
>>> m1.save()
>>> beatles.members.all()
[<Person: Ringo Starr>]

>>> p = beatles.members.all()[0]
>>> p
[<Person: Ringo Starr>]

我想得到p的date_joined值,我知道可以通过

来完成
>>> Membership.objects.get(person=p, group=beatles).date_joined
datetime.date(1962, 8, 16)

但是可以简单地得到它:

>>> p.xxx(*args)

=============== models.py ================

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

1 个答案:

答案 0 :(得分:1)

来自documentation page you link to

访问相同信息的另一种方法是从Person对象查询多对多反向关系:

>>> ringos_membership = ringo.membership_set.get(group=beatles)
>>> ringos_membership.date_joined
datetime.date(1962, 8, 16)
>>> ringos_membership.invite_reason
'Needed a new drummer.'