如何从多个关系表中获取第三个属性?

时间:2013-11-04 04:14:26

标签: python django django-models django-queryset

我在python django框架中有模型,如:

class PropertyTaxItem(models.Model):
     property = models.ForeignKey(Property)

class Property(models.Model):
     citizens = models.ManyToManyField(Citizen, null=True, through = 'Ownership',help_text="a property could belong to multiple citizens")

class Ownership(models.Model):
    as_property=models.ForeignKey(Property,null=True,blank=True, related_name='assets')
    owner_citizen=models.ForeignKey(Citizen,null=True,blank=True, related_name="hs")
    date_started = models.DateField(default=datetime.now())
    date_ended = models.DateField(blank=true)

class Citizen(models.Model):
     first_name = models.CharField(max_length = 50, help_text = 'First name')
     last_name = models.CharField(max_length = 50, help_text = 'Last name')

我想从PropertyTaxItem获取表格:

items = PropertyTaxItem.objects.filter(i_status='active').select_related('property').prefetch_related('property__citizens')

我可以通过以下方式获得公民:

for i in items:
    citizens=i.property.citizens.all()

但如何获得每个公民的Ownership.date_started和Ownership.date_ended?

1 个答案:

答案 0 :(得分:0)

这里是Django的official documentation of queries

基于它: citizens.objects.get(ownership__date_started)等等。