跨多个模型的外键过滤

时间:2018-11-11 12:47:49

标签: django

我有以下四个模型和在forms.py中定义的表单。有一个模型(CodeVillage)列出了一些村庄。模型CodePlaces列出了每个村庄周围的许多地方。样板房包含一些居住在村庄中的家庭的详细信息。样板职业具有有关各个家庭成员及其职业的记录。

占领表格用作家庭管理表格的内联。我希望过滤掉表单中的work_place外键,以便它仅显示特定家庭所居住的村庄周围的地方。我无法弄清楚如何正确地获取从家庭模型的相关记录中选择村庄,然后从代码位置模型的相关记录中选择地点的查询集。

非常感谢您在修复此过滤器方面的任何帮助。

models.py

class CodeVillage(models.Model):
    village_name = models.CharField(max_length=150, null=True, blank=True)
    def __unicode__(self):
        return self.village_name
    def __str__(self):
        return self.village_name


class CodePlaces(models.Model):
    village =  models.ForeignKey(CodeVillage, blank=True,  on_delete=models.SET_NULL, null=True)
    place = models.CharField(max_length=150)
    district = models.CharField(max_length=150, null=True, blank=True)
    state = models.CharField(max_length=150, null=True, blank=True)
    class Meta:
        unique_together = (("location","place"),)
    def __unicode__(self):
        return '%s (%s)' % (self.location, self.place)
    def __str__(self):
        return '%s (%s)' % (self.location, self.place)

class Household(models.Model):
    village =  models.ForeignKey(CodeVillage, blank=True,  on_delete=models.SET_NULL, null=True)
    household_number = models.IntegerField(blank=True, null=True)
    head_of_household = models.CharField(max_length=150, null=True, blank=True)

class occupations(models.Model):
    sno = models.ForeignKey(Household,on_delete=models.CASCADE)
    person_number = models.IntegerField(blank=True, null=True)
    name = models.CharField(max_length=150, null=True, blank=True)
    occupation = models.CharField(max_length=100, null=True, blank=True)
    work_place  = models.ForeignKey(CodePlaces, blank=True, on_delete=models.SET_NULL, null=True)
    class Meta:
        unique_together = (("sno", "person_number","occupation"),)

forms.py

class occupations_form(ModelForm):
    def __init__(self,*args,**kwargs):
        super (occupations_form,self).__init__(*args,**kwargs)
        self.fields['work_place'].queryset = CodePlaces.objects.filter(village=occupations__household.instance.village_id)
    class Meta:
        model = occupations
        fields = '__all__'

1 个答案:

答案 0 :(得分:0)

这似乎可以解决问题:

self.fields['work_place'].queryset = CodePlaces.objects.filter(village__household__id=self.instance.sno_id)