prongs
prongs

Reputation: 9606

django manager get any one object

In a many-one model, I want to get only one of the objects(any one object) from the manager, how to do that?

models.School.student_set.any_one()

I did not find any such method in the documentation. right now I am doing something like:

models.School.student_set.all()[0]

which I believe to be inefficient.

Upvotes: 1

Views: 406

Answers (1)

jkozera
jkozera

Reputation: 3066

QuerySets are not evaluated until you actually get some data from them, so slicing the result of all() is actually going to be efficient.

See docs on QuerySets - "No database activity actually occurs until you do something to evaluate the queryset.". Also documenation on limiting QuerySets mentions your case explicitly.

If you feel adventurous, you can verify it yourself by looking at django.db.connection.queries (docs)

Upvotes: 4

Related Questions