Msencenb
Msencenb

Reputation: 5104

Check if object exists within QuerySet

So I have a User model and a Dinner model. They are associated by a LotteryEntry model. (aka people have to enter a lottery to be chosen to go to a dinner)

Lets say I have a query set of Dinners like this:

first_page_dinners = Dinner.objects.all().order_by('-created_at')[:5]

And the QuerySet of 'lotteries' for the currently logged in user

entries = LotteryEntry.objects.filter(user=request.user)

Now in the template I am looping through the Dinner objects, but also want to check if the person has already entered a lottery for that dinner... so something like this:

{% for d in dinners %}
   {% if entries.contains(d) %}
   //custom html here if user has already entered lottery
   {% endif %}
{% endfor %}

However the '.contains' isn't a real thing. Does django/python provide a nice little method like this?

Upvotes: 3

Views: 4880

Answers (2)

dannyroa
dannyroa

Reputation: 5571

Try using values_list, so it would be easier to check if an object exists:

dinner_entries = LotteryEntry.objects.filter(user=request.user).values_list('dinner__id', flat=True)

In your template, you can check like this:

{% if d.id in dinner_entries %}

Upvotes: 5

fviktor
fviktor

Reputation: 2958

It is a bit hard to answer your question without knowing your data model in a bit more detail, but I try to do so nevertheless:

Slow, but should work: Try to iterate on your lottery entries for each dinner, then look for your foreign key field in your LotteryEntry record. If the dinner referenced matches the dinner record form the outer loop, then your're there.

If you want a faster solution, then you need to prepare a dictionary based on your entries query set mapping the dinner records to the corresponding LotteryEntry ones. Then you can use this map to look up the corresponding lottery entry by invoking the dictionary's get method. If there is no lottery entry, then you will just get None.

Upvotes: 0

Related Questions