Two QuerySets on a FormSet

22 views
Skip to first unread message

Some Developer

unread,
Jan 9, 2015, 11:19:01 AM1/9/15
to django...@googlegroups.com
I have a model Song which has a FormSet associated with it using a
ModelForm.

The Song model has two ForeignKeys (Artist and Album) but I want to
limit the options shown in the FormSet to only Artists and Albums made
by the currently logged in user. I know to make the QuerySets themselves
but I don't know how to associate the two QuerySets with the FormSet.

I know you can specify one QuerySet by editing the ModelForm instance
but I don't see how I would get the current logged in user when doing
this and as I said this only lets you specify one QuerySet rather than
the two I require as far as I understand it.

Any help is appreciated.

Collin Anderson

unread,
Jan 12, 2015, 3:46:31 PM1/12/15
to django...@googlegroups.com
Hi,

You can merge the two querysets like this. Would that help?

qs = Song.objects.filter(artist__made_by=request.user) | Song.objects.filter(album__made_by=request.user)

or use models.Q

from django.db.models import Q
qs
= Song.objects.filter(Q(artist__made_by=request.user) | Q(album__made_by=request.user))

Collin

Some Developer

unread,
Jan 16, 2015, 10:46:15 AM1/16/15
to django...@googlegroups.com
On 12/01/15 20:46, Collin Anderson wrote:
> Hi,
>
> You can merge the two querysets like this. Would that help?
>
> |
> qs
> =Song.objects.filter(artist__made_by=request.user)|Song.objects.filter(album__made_by=request.user)
> |
>
> or use models.Q
>
> |
> fromdjango.db.models importQ
> qs
> =Song.objects.filter(Q(artist__made_by=request.user)|Q(album__made_by=request.user))
> |
>
> Collin
>

That's cool. I didn't realise you could do that.

I decided in the end to simplify my form code as I it would have taken
too long for a user to upload 10 songs on the same page especially in
FLAC format so I moved to single form (even though it makes the whole
process much more difficult for the user) and will hope for the best.

Anyway this is only a minimum viable product to see if the business idea
will work.

Thanks for the suggestion.

Reply all
Reply to author
Forward
0 new messages