开发者

Django model: How to access "join table"?

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

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(ma开发者_高级运维x_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

So basically what I want to do here is access person/group/data_joined/invite_reason from a group object, how to write such a code? Thanks~


It's a standard reverse ForeignKey relationship:

my_group.membership_set.all() 


Hope you can use intertools


import itertools

queryset = itertools.chain(Person.objects.filter(manytomany__isnull=False).order_by('name'),
                           Group.objects.filter(manytomany__isnull=False).order_by('name'),
                           Membership.objects.filter(manytomany__isnull=True).order_by('date_joined')) 

Sultan

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜