基本 Django 查询

Basic Django Query

简单的场景,但不知道如何查询:

我们有一个 Store 模型和 Transaction 模型。 Foreign KeyTransaction 模型上与 Store 相关。

我想查询以下列表: 家当天完成了至少一次 交易的商店。应排除所有其他商店。


Store.objects.filter(transaction__gt=0, transaction__date_created__gt='2016-06-01')

当我尝试前一个查询时,我得到了一个很长的列表:

[<Store: TrialStore>, <Store: TrialStore>, <Store: TrialStore>, ... ]

它几乎就像是为每笔交易列出商店的一个实例。我想要返回的只是一份 每家商店 的列表,这些商店 当天至少完成了一笔交易。

现在,数据库中只有一家商店,所以我应该只返回一个结果。

编辑

Store 型号:

class Store(models.Model):
  status = models.IntegerField(choices=status_choices, default=ACTIVE_STATUS)
  legal_name = models.TextField(verbose_name='Legal Name')
  mobile_number = PhoneNumberField(blank=True)
  email_address = models.EmailField(blank=True)

Transaction 型号:

class Transaction(models.Model):
  store = models.ForeignKey(Store)
  date_created = models.DateTimeField(auto_now_add=True, verbose_name='Created')
  status = models.IntegerField(choices=status_choices)

这个呢?

Store.objects.filter(
    transaction__gt=0, 
    transaction__date_created__year='2016', 
    transaction__date_created__month='06',
    transaction__date_created__day='01'
)

在您的查询中,您说的是 "give me all stores that have transactions since 2016.06.01"。根据我的查询,"give me all stores that have transactions from this day"

您可以在查询时将日期时间字段转换为date

Store.objects.filter(transaction__date_created__date=Date(2016, 1, 1))

你应该使用 distinct():

Store.objects.filter(transaction__gt=0,
                     transaction__date_created__gt='2016-06-01').distinct()