获得至少包含一张图片的产品

时间:2014-06-24 01:04:33

标签: python django

我的模特看起来像这样:

class Product(models.Model):
    name = models.CharField(max_length=100)
    ...

class ProductImage(models.Model):
    thumbnail = models.ImageField(...)
    ...
    product = models.ForeignKey(Product, related_name='images', blank=True, null=True)

我需要更改以下内容,使其仅获取至少包含一张图片的产品:

products = Product.objects.filter(status='PU').order_by('?')[:4]

2 个答案:

答案 0 :(得分:2)

注释,然后过滤注释。 https://docs.djangoproject.com/en/dev/topics/db/aggregation/

Product.objects.annotate(image_count=Count('images')).filter(image_count__gt=0)

答案 1 :(得分:2)

试试这个:

products = Product.objects.filter(status='PU', images__isnull=False).order_by('?')[:4]