Check if object exists within QuerySet

django, django-queryset, for-loop, python

Solution

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 %}

Problem

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?

Original source