2010-12-20 80 views
1

我有一個簡單的問題。使用上面的django的例子。我怎樣才能得到例如從一個組的人的invite_reason?或所有加入日期都是來自該人員的所有羣組?謝謝。訪問中介模型值Django

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

    def __unicode__(self): 
     return self.name 

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

    def __unicode__(self): 
     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) 

回答

2

你需要查詢您爲Membership模型,就像這樣:

memberships = Membership.objects.filter(person=person, group=group) 
for membership in memberships: 
    membership.invite_reason 

另外,還可以基於關係查詢它:

memberships = person.membership_set.filter(group=group) 
for membership in memberships: 
    membership.invite_reason 
+0

感謝您的幫助! – 2010-12-24 19:20:11