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ここで、少なくとも1つが関連付けられているすべてのをクエリしたいと思いますEntry(かなり風変わりだと思います)。

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

これは非常にうまく機能します。datetimeしかし、このクエリを2つのsstartとで指定された日付/時刻ウィンドウ検索と組み合わせたいと思いますend。私が思いついたのは:

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の順序を並べ替えるだけで、コンテンツは並べ替えません。日付/時刻検索を実行するにはどうすればよいですか(できれば1つのクエリだけで)?

4

1 に答える 1

1

逆FK(およびManyToManyフィールドも)の場合、

.filter(a=b, x=y)および.filter(a=b).filter(x=y)ドキュメントを参照)。

start両方のend条件がある場合に必要なのは、両方の条件を検証する少なくとも1つの条件を持つものfilter(.,.)を取得するものです。CollectionsEntry

また、Collection.objects.filter(entries__isnull=False).distinct()より読みやすいようです.annotate(entry_count=Count('entries')).filter(entry_count__gt=0)

最後に、に少なくとも1つの条件がentriesある場合、そのようなエントリの存在を確認するためのフィルタは必要ありません。

于 2013-01-15T14:32:18.957 に答える