qarthandso
qarthandso

Reputation: 2188

Basic Django Query

Simple scenario but can't figure out how to query for it:

We have a Store model and Transaction model. Foreign Key on Transaction model relating back to Store.

I want to query for a list of: Only stores that have done at least one transaction that day. All other stores should be excluded.


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

When I tried the former query, I got a long list back:

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

It's almost as if it's listing an instance of the store for each transaction. All I want back is a list of each store that has done at least one transaction for that day.

Right now, there's only one store in the database, so I should only be getting back one result.

Edit

Store Model:

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 Model:

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)

Upvotes: 1

Views: 63

Answers (3)

Caique Reinhold
Caique Reinhold

Reputation: 36

You should use distinct():

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

Upvotes: 2

AKS
AKS

Reputation: 19861

You can cast the datetime field as date while querying:

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

Upvotes: 1

doniyor
doniyor

Reputation: 37934

what about this?

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

in your query, you are saying "give me all stores that have transactions since 2016.06.01". With my query, "give me all stores that have transactions from this day"

Upvotes: 0

Related Questions