Martin
Martin

Reputation: 291

Django QuerySet order

I am new to both django and python but I am beginning to get a grasp on things. I think.

I have this problem and I can not seem to find an answer to it. (Though I assume it is really simple and the limiting factors are my google skills and lack of python/django knowledge)

The scenario:

a user can opt in to recieve temporary job openings at any number of stores he or she chooses.

I would like to present a list of upcoming job openings (StoreEvents) sorted by the DateField only.

Example: 
    Store A - 2009-04-20 
    Store B - 2009-04-22
    Store A - 2009-04-23

Atm I am stuck with presenting the data first sorted by store then by date since I am obviously accessing the StoreEvents through the Store model.

Example:
    Store A - 2009-04-20
    Store A - 2009-04-23
    Store B - 2009-04-22

So my question is: Is it possible to create a QuerySet that looks like the first example and how do I do it?

Examples of related models included:

class Store(models.Model):

class StoreEvent(models.Model):
    info = models.TextField()
    date = models.DateField()
    store = models.ForeignKey(Store, related_name='events')

class UserStore(models.Model):
    user = models.ForeignKey(User, related_name='stores')
    store = models.ForeignKey(Store, related_name='available_staff')

Edit:

The following SQL does the trick but I still can't figure out how to do it in django:

SELECT *
FROM store_storeevent
WHERE store_id
IN (
    SELECT store_id
    FROM profile_userstore
    WHERE user_id =1
)
ORDER BY date

Upvotes: 20

Views: 50708

Answers (3)

Martin
Martin

Reputation: 291

Thanks for your help guys, finally figured it out:

qs = StoreEvent.objects.filter(
    store__in=Store.objects.filter(
        available_staff__in=UserStore.objects.filter(user=user)
    )
).order_by('date')

it results in 3 SQL SELECTs but does the trick...

Upvotes: 9

Andrea Di Persio
Andrea Di Persio

Reputation: 3266

queryset = StoreEvent.objects.filter(store__in=UserStore.objects.filter(user__id=1).store).order_by('store__name', '-date')

or more graciously

user = User.objects.get(username="foo")
user_stores = user.stores.all()

store_events = StoreEvent.objects.filter(store__in=user_stores).order_by('store__name', '-date')

Upvotes: 1

Harold
Harold

Reputation: 5325

Order by Date for all users:

queryset = StoreEvent.objects.all().order_by('-date')

To filter by user:

queryset = StoreEvent.objects.filter(stores__user=request.user).order_by('-date')

Upvotes: 47

Related Questions