[Answered ]-How to get a list of of objects of a Django model using a field that itself is a foreign key?

2👍

Based on your models, seems it’s:

Article.objects.filter(category__main_category__main_category='Entertainment')

You have some indirection in your models, so here’s a diagram:

Article.objects.filter(category__main_category__main_category='Entertainment')
                       ^         ^               ^ 
                       |         |               |_ MainCategory.main_category
                       |         |_ Subcategory.main_category
                       |_ Article.category                     

Your error The error is invalid literal for int() with base 10: 'Entertainment' is simply because you were querying for category__main_category which is an FK to Subcategory so it was trying to convert that to a primary key (e.g. an int)

Django docs on relationships querying https://docs.djangoproject.com/en/1.8/topics/db/queries/#lookups-that-span-relationships

👤bakkal

0👍

You are getting the error because category__main_category expects a MainCategory instance or its primary key. So it should be:

Article.objects.filter(category__main_category__main_category = 'Entertainment')

Also to get “all the articles that have the same main_category” you would have to actually do

Article.objects.filter(category__main_category=category_instance)

where category_instance sholud be selected from a category list provided somewhere to the app user. Otherwise you are just searching by main category name which does not identify a category because it is not marked as primary key or unique.

👤Ivan

Leave a comment