Search code examples
djangodjango-queryset

difference between values() and only()


what's the difference between using:

Blabla.objects.values('field1', 'field2', 'field3')

and

Blabla.objects.only('field1', 'field2', 'field3')

Solution

  • Assuming Blabla has the fields in your question, as well as field4,

    Blabla.objects.only('field1', 'field2', 'field3')[0].field4
    

    will return the value of that object's field4 (with a new database query to retrieve that info), whereas

    Blabla.objects.values('field1', 'field2', 'field3')[0].field4
    

    will give

    AttributeError: 'dict' object has no attribute 'field4'
    

    This is because .values() returns a QuerySet that returns dictionaries, which is essentially a list of dicts, rather than model instances (Blabla).