0

My models.py is something like this:

class Department(models.Model):
    name = models.CharField(max_length=255)

class Category(models.Model):
    name = models.CharField(max_length=255)
    department = models.ForeignKey(Department, related_name="categories")

class Product(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, related_name="products")

As you can see, the product model does not have a direct connection to the department, it only has one through the category model. However, in my department details for < Department X >, I want to get all the products that have a category that has the department < Department X >. Is there any way to do it with one query? I don't want to use a for loop for this. Thanks!

2 Answers 2

3

You can use the double underscore notation to look up fields in related models, for example:

department = Department.objects.get(name='X')
products = Product.objects.filter(category__department=department)

Or, if you don't already have the department instance, you can filter by department name:

products = Product.objects.filter(category__department__name='X')
Sign up to request clarification or add additional context in comments.

Comments

2

Maybe something like this:

Product.objects.filter(category__department=<DepartmentX>)

5 Comments

@mohammedqudah i dont think we need to delete this, since they are not the same answer
yeh but the <DepartmentX> require one more line of code ;0
The question already mentions the <departmentx> thing, so I suppose we don't need to mention that in the answer, and in addition to the question is not about fetching the <DepartmentX>
@mohammedqudah it's ok to have more than one answer to a question, please don't ask users to delete their answers. In the view, there's a good chance that the department will have been fetched already, so querying category__department=<DepartmentX> is a good approach.
i am sorry. : )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.