2014-06-24 44 views
0

我的模式是这样的:让产品与至少一个图像

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

试试这个:

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

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

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

不完全是,需要改变' 'productimage'',以符合他'related_name',所以'IMAGE_COUNT =计数(' 图像)' – Shay

+0

@ shay,很好,赶上! –

相关问题