Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the first() method and slices works differently in Django?

I have the model:

class PhotoAlbum(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, auto_created=True)
    name = models.CharField(max_length=50, verbose_name='Album name')
    type = models.ForeignKey(AlbumType, on_delete=models.CASCADE, verbose_name='Album type')
    created_at = models.DateTimeField(auto_now_add=True)

And i have this code:

print(PhotoAlbum.objects.all().first())
print(PhotoAlbum.objects.all()[:1].get())

it seemed to me that the same objects should be displayed, but different ones are returned.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What’s going on, isn’t it an identical design?

>Solution :

If the queryset is not ordered then first() orders the queryset by the primary key

from django.db import connection
Pet.objects.all().first()
print(connection.queries[-1]['sql'])
# SELECT ... FROM <table> ORDER BY <table>."id" ASC LIMIT 1

But slicing the queryset performs no such default ordering

from django.db import connection
Pet.objects.all()[:1].get()
print(connection.queries[-1]['sql'])
# SELECT ... FROM <table> ASC LIMIT 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading