1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.