John Smith
John Smith

Reputation: 2738

Django query with random

In views.py

I want to randomly choose one record with my filter:

a=Entry.objects.filter(first_name__contains='Br')).order_by('?')[0]
b=a.id
c=Entry.objects.filter(first_name__contains='Br')).order_by('?')[0]
d=c.id

It is possible that b and d are same.

But my goal is to get each time different entry object and id. How can I do this?

Upvotes: 1

Views: 144

Answers (1)

Alasdair
Alasdair

Reputation: 308999

How about fetching both objects in the same query? That way you know you have two distinct entries.

a, c = Entry.objects.filter(first_name__contains='Br')).order_by('?')[0:2]
b = a.id
d = c.id

Note that this will raise a ValueError if the filter matches fewer than two entries.

Upvotes: 2

Related Questions