简体   繁体   English

如何通过Django中的另一个ForeignKey使用ForeignKey字段获取对象?

[英]How to get objects using a ForeignKey field through another ForeignKey in Django?

My models.py is something like this: 我的models.py是这样的:

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 > . 但是,在我的<部门X>的部门详细信息中,我想获得所有具有部门<部门X>类别的产品。 Is there any way to do it with one query? 有什么办法可以完成一个查询吗? I don't want to use a for loop for this. 我不想为此使用for循环。 Thanks! 谢谢!

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: 或者,如果您还没有department实例,则可以按部门名称进行过滤:

products = Product.objects.filter(category__department__name='X')

也许是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM