django 过滤器获取父子关系

django filter get parent to child

我正在使用 django(3.1.5)。我正在尝试通过过滤器查询将父模型转换为子模型 我有这样的模型 -

class Product(models.Model):
   product_name = models.CharField(max_length=255, unique=True)
   is_feature = models.BooleanField(default=False)
   is_approved = models.BooleanField(default=False)
   created_at = models.DateTimeField(auto_now_add=True)

class ProductGalleryImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    product_gallery_image = models.FileField(upload_to='path')
    is_feature = models.BooleanField(default=False)

我正在从 SELECT * FROM products_product AS pp INNER JOIN products_productgalleryimage AS ppgi ON ppgi.product_id = pp.id WHERE ppgi.is_feature=1 AND pp.is_feature=1 AND is_approved=1 ORDER BY pp.created_at LIMIT 4 mysql 查询中获取数据。

那么我如何在 Django 过滤器查询中获取像这个查询这样的数据

首先,您可以将 related_name 添加到 ProductGalleryImage 以获得更好的查询支持,例如这样

product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_images')

那么你的查询应该是这样的

products=Product.objects.filter(is_approved=True, is_feature=True, product_images__is_feature=True).order_by('created_at')[:4]

您可以像这样简单地遍历其他相关模型:

for product_gallery_image in product_instance.productgalleryimage_set.all():
    print(product_gallery_image.product_gallery_image)

这里的productgalleryimage_set只是相关型号的小写名称加上_set。您可以通过在外键上设置 related_name 属性来更改它。
注意:这将执行查询以获取某些产品实例的每个 product_gallery_image 对象。

如果只想获取第一个对象:

product_gallery_image = product_instance.productgalleryimage_set.first()

如果你想像你的例子那样执行一个连接,它只会执行一个查询,你可以使用 select_related (this will only work in forward direction for reverse direction look at prefetch_related):

product_gallery_images = ProductGalleryImage.objects.all().select_related('product')
for product_gallery_image in product_gallery_images:
    print(product_gallery_image.product.product_name)
    print(product_gallery_image.product_gallery_image)