Fastest way to get the first object from a queryset in django?

前端 未结 8 1096
有刺的猬
有刺的猬 2020-12-12 09:17

Often I find myself wanting to get the first object from a queryset in Django, or return None if there aren\'t any. There are lots of ways to do this which all

相关标签:
8条回答
  • 2020-12-12 09:44

    This could work as well:

    def get_first_element(MyModel):
        my_query = MyModel.objects.all()
        return my_query[:1]
    

    if it's empty, then returns an empty list, otherwise it returns the first element inside a list.

    0 讨论(0)
  • 2020-12-12 09:46

    Now, in Django 1.9 you have first() method for querysets.

    YourModel.objects.all().first()
    

    This is a better way than .get() or [0] because it does not throw an exception if queryset is empty, Therafore, you don't need to check using exists()

    0 讨论(0)
  • 2020-12-12 09:53
    r = list(qs[:1])
    if r:
      return r[0]
    return None
    
    0 讨论(0)
  • 2020-12-12 09:53

    You should use django methods, like exists. Its there for you to use it.

    if qs.exists():
        return qs[0]
    return None
    
    0 讨论(0)
  • 2020-12-12 09:57

    You can use array slicing:

    Entry.objects.all()[:1].get()
    

    Which can be used with .filter():

    Entry.objects.filter()[:1].get()
    

    You wouldn't want to first turn it into a list because that would force a full database call of all the records. Just do the above and it will only pull the first. You could even use .order_by() to ensure you get the first you want.

    Be sure to add the .get() or else you will get a QuerySet back and not an object.

    0 讨论(0)
  • 2020-12-12 09:59

    If you plan to get first element often - you can extend QuerySet in this direction:

    class FirstQuerySet(models.query.QuerySet):
        def first(self):
            return self[0]
    
    
    class ManagerWithFirstQuery(models.Manager):
        def get_query_set(self):
            return FirstQuerySet(self.model)
    

    Define model like this:

    class MyModel(models.Model):
        objects = ManagerWithFirstQuery()
    

    And use it like this:

     first_object = MyModel.objects.filter(x=100).first()
    
    0 讨论(0)
提交回复
热议问题