Django加入查询 - 仅显示一个或多个帖子的类别

时间:2018-05-18 18:36:02

标签: python django

您好我正在尝试获取有关联接查询的帮助。

我有交易模型和零售商模型。零售商模型是我的交易模型的外键。看起来像这样

class Deal(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=140, unique=True)
    description = RichTextUploadingField(default='')
    retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE)
    image = VersatileImageField('deal image',
                               upload_to=deal_upload_path,
                               null=True,
                               blank=True)
    img_alt = models.CharField(max_length=140, default='')
    link = models.URLField(max_length=2000, default='')
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    date_added = models.DateField(default=timezone.now)
    date_expires = models.DateField(default=timezone.now)
    price = models.CharField(max_length=140)
    secondary_price = models.CharField(max_length=140, default='')
    likes_total = models.IntegerField(default=1)
    expired = models.BooleanField(default=False)
    handpicked = models.BooleanField(default=False)

class Retailer(models.Model):
    company = models.CharField(max_length=140)
    slug = models.SlugField()

我只是想获得一份至少有一笔交易的零售商名单。

我有一个看起来像这样的context_processor但是我很难确定将其更改为我需要的最佳方法。有什么想法吗?

def retailers(request):
    return {
        'stores': Retailer.objects.all().order_by('company')
    }

2 个答案:

答案 0 :(得分:2)

您可以将exclude()与交易related_query_nameisnull查询一起使用:

Retailer.objects.exclude(deal__isnull=True).order_by('company')

<强> UPD

您还可以使用filter根据需要合并多个条件,并distinct从结果中删除重复项:

Retailer.objects.filter(deal__isnull=False, deal__date_expires__gte=today).order_by('company').distinct()

答案 1 :(得分:1)

一种简单的方法是使用Annotations。 Django ORM Cookbook有一个很好的部分。

from django.db.models import Count

queryset = Retailer.objects.annotate(
    deal_count=Count('deal')
).exclude(deal_count=0)

添加一个可以像其他任何一样使用的字段。