Reverse access model through a “double” ForeignKey

15 views
Skip to first unread message

Gergely Polonkai

unread,
Oct 14, 2015, 9:13:10 AM10/14/15
to Django users
Hello,

I have three models:

• Build
• BuildGrouping, with a ForeignKey “build” pointing to Build
• Value, with a ForeignKey “grouping” that points to BuildGrouping

Right now, I also have Value.build, which is a ForeignKey to Build, so I can access the list of Values directly from a Build.

This setup, though, doesn’t feel right, as it contains redundancy. Is there a way to access the list of Values directly from Build without having this redundancy?

Thank you in advance!

Best,
Gergely

Carsten Fuchs

unread,
Oct 14, 2015, 1:10:03 PM10/14/15
to django...@googlegroups.com
Am 14.10.2015 um 11:11 schrieb Gergely Polonkai:
> This setup, though, doesn’t feel right, as it contains redundancy. Is there a way to
> access the list of Values directly from Build without having this redundancy?

Well, you can filter your Value queryset by Build, see
https://docs.djangoproject.com/en/1.8/topics/db/queries/#lookups-that-span-relationships

Or, starting with a Build instance, you can work towards the Value instances, see
https://docs.djangoproject.com/en/1.8/topics/db/queries/#related-objects

Best regards,
Carsten

Vijay Khemlani

unread,
Oct 14, 2015, 1:10:12 PM10/14/15
to django...@googlegroups.com
Value.objects.filter(grouping__build=your_build) I guess

You can add it as a method to the Build class

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACczBU%2BCCSPDbH6Q%2Bn-n9r0kQjYHKrAMQgVWd6mFPjLfZhoULg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Gergely Polonkai

unread,
Oct 14, 2015, 2:06:19 PM10/14/15
to Django users
Hello,

I just solved it, and went with a @property. On Build I have:

@property
def values(self):
    return Value.objects.filter(grouping__build=self)

and on the Value I have:

@property
def build(self):
    return self.grouping.build

This way I stay backwards compatible and didn’t even have to change my templates and such. Thanks for the tips, though!

Best,
Gergely

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
Reply all
Reply to author
Forward
0 new messages