Foreignkey filtering spanning across multiple models









up vote
0
down vote

favorite












I have following four models and a form defined in forms.py. There is a model (CodeVillage) that lists some villages. Model CodePlaces lists a number of places around each village. Model Households contains some details of households living in villages. Model occupations has records for various members of households and their occupations.



The occupations_form is used as an inline in admin form for households. I would like the work_place foreignkey in the form filtered so that it shows only places around the village in which a particular household lives. I am unable to figure out how to correctly get the queryset that will pick village from related record in household model, and then pick places from the related record in codeplaces model.



Would really appreciate any help in fixing this filter.



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__'









share|improve this question



























    up vote
    0
    down vote

    favorite












    I have following four models and a form defined in forms.py. There is a model (CodeVillage) that lists some villages. Model CodePlaces lists a number of places around each village. Model Households contains some details of households living in villages. Model occupations has records for various members of households and their occupations.



    The occupations_form is used as an inline in admin form for households. I would like the work_place foreignkey in the form filtered so that it shows only places around the village in which a particular household lives. I am unable to figure out how to correctly get the queryset that will pick village from related record in household model, and then pick places from the related record in codeplaces model.



    Would really appreciate any help in fixing this filter.



    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__'









    share|improve this question

























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have following four models and a form defined in forms.py. There is a model (CodeVillage) that lists some villages. Model CodePlaces lists a number of places around each village. Model Households contains some details of households living in villages. Model occupations has records for various members of households and their occupations.



      The occupations_form is used as an inline in admin form for households. I would like the work_place foreignkey in the form filtered so that it shows only places around the village in which a particular household lives. I am unable to figure out how to correctly get the queryset that will pick village from related record in household model, and then pick places from the related record in codeplaces model.



      Would really appreciate any help in fixing this filter.



      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__'









      share|improve this question















      I have following four models and a form defined in forms.py. There is a model (CodeVillage) that lists some villages. Model CodePlaces lists a number of places around each village. Model Households contains some details of households living in villages. Model occupations has records for various members of households and their occupations.



      The occupations_form is used as an inline in admin form for households. I would like the work_place foreignkey in the form filtered so that it shows only places around the village in which a particular household lives. I am unable to figure out how to correctly get the queryset that will pick village from related record in household model, and then pick places from the related record in codeplaces model.



      Would really appreciate any help in fixing this filter.



      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__'






      django






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 13:36

























      asked Nov 11 at 12:47









      len71

      162




      162






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          This seems to do the trick:



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





          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248894%2fforeignkey-filtering-spanning-across-multiple-models%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            This seems to do the trick:



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





            share|improve this answer


























              up vote
              0
              down vote













              This seems to do the trick:



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





              share|improve this answer
























                up vote
                0
                down vote










                up vote
                0
                down vote









                This seems to do the trick:



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





                share|improve this answer














                This seems to do the trick:



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






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 11 at 16:55

























                answered Nov 11 at 15:45









                len71

                162




                162



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53248894%2fforeignkey-filtering-spanning-across-multiple-models%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    How to read a connectionString WITH PROVIDER in .NET Core?

                    Node.js Script on GitHub Pages or Amazon S3

                    Museum of Modern and Contemporary Art of Trento and Rovereto