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?
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.
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With