1

我有以下型号:

class Collection(models.Model):
    # some fields here ...

class Entry(models.Model):
    collection = models.ForeignKey(Collection, reverse_name="entries")
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()

现在我想查询所有Collection至少有一个Entry关联的 s(我认为这很古怪):

collections_qs = Collection.objects.annotate(
    entry_count=Count('entries')
).filter(entry_count__gt=0)

效果很好。但我想将此查询与两个datetimesstartend. 我想出的是:

if start:
    collections_qs = collections_qs.filter(entries__start_time__gte=start)
if end:
    collections_qs = collections_qs.filter(entriess__end_time__lte=end)

但这只是重新排列返回Collection的 s 的顺序而不是内容。如何实现日期/时间搜索(最好只使用一个查询)?

4

1 回答 1

1

对于反向 FK(以及 ManyToMany 字段),两者之间存在差异

.filter(a=b, x=y).filter(a=b).filter(x=y)(见文档)。

当您同时拥有startend条件时,您需要的是filter(.,.)能够让您获得Collections至少具有Entry验证这两个条件的条件。

此外,Collection.objects.filter(entries__isnull=False).distinct()似乎比.annotate(entry_count=Count('entries')).filter(entry_count__gt=0).

最后,当您至少有一个条件时entries,您不需要任何过滤器来检查此类条目是否存在。

于 2013-01-15T14:32:18.957 回答