views:

1080

answers:

3

Hi, 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
+2  A: 

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')
Harold
Thanks Harold, but that would give me any StoreEvent sorted by date. I need to fetch only the ones of interest to the user controlled by the UserStore model.
Martin
I updated my answer.
Harold
A: 
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')
Andrea Di Persio
Thanks Andrea, but this doesn't seem to do it, though I guess it is close. Both your examples results in an empty queryset even though there are listed events for the stores selected by the user in question
Martin
A: 

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...

Martin