Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: getting FIRST item that belongs to a model object in a ManyToManyField

Having a model po with a ManyToManyField called Order.

I am considering some options including the following solutions:

po.Orders.all()[0].itemname

but I am not sure if this solution will be expensive (or not?) basically its querying for the whole table then filter out the first item.

Second solution

po.Orders.get(pk=1).itemname

This one seem less expensive but doesn't work because its not possible to know the pk before hand.

I'm wondering if there are other solutions that will obtain ANY item having the ManyToMany relationship with the po object?

like image 309
40pro Avatar asked Dec 07 '22 07:12

40pro


2 Answers

It's not true that using [0] queries the whole table. As stated in the documentation, slicing a queryset passes a LIMIT/OFFSET to the database query, so this is perfectly efficient.

like image 149
Daniel Roseman Avatar answered Apr 23 '23 05:04

Daniel Roseman


.first() is new in the Django Development version. See the docs: https://docs.djangoproject.com/en/dev/ref/models/querysets/#first

Until it's out as stable, or you run the dev version, stick with what you have. The QuerySet is lazy, and "should" take the least-work approach. If you're concerned, check your query log in the MySql General Log.

(from the docs)

Note that first() is a convenience method, the following code sample is equivalent to the above example:

try:
p = Article.objects.order_by('title', 'pub_date')[0]
except IndexError:
p = None

like image 33
Joe Frambach Avatar answered Apr 23 '23 05:04

Joe Frambach