Interview question
What is the difference between values(), values_list(), and regular QuerySets? values(), values_list(), और regular QuerySets में क्या अंतर है?
Answer
| Method | Returns | Element type |
|---|---|---|
| Regular QuerySet | Full model instances | Model objects with all fields/methods |
| values() | Dictionaries | {'field': value, ...} per row |
| values_list() | Tuples (or flat values with flat=True) | (value1, value2, ...) per row |
# Regular QuerySet - full model instances, more memory, full functionality
books = Book.objects.all()
for book in books:
print(book.title, book.get_absolute_url()) # can call model methods
# values() - dictionaries, useful for APIs or when you only need specific fields
book_dicts = Book.objects.values('title', 'price')
# [{'title': 'Django Basics', 'price': Decimal('25.99')}, ...]
for b in book_dicts:
print(b['title'])
# values_list() - tuples, more compact than dicts
book_tuples = Book.objects.values_list('title', 'price')
# [('Django Basics', Decimal('25.99')), ...]
# flat=True - use ONLY when selecting a SINGLE field, gives a flat list
titles = Book.objects.values_list('title', flat=True)
# ['Django Basics', 'Advanced Django', ...]
# Performance benefit: values()/values_list() skip creating full model
# instances, reducing memory usage and query overhead for large datasets
# when you only need a subset of fields
# Useful for populating dropdowns or simple lookups
author_names = Author.objects.values_list('name', flat=True).distinct()
# only() and defer() - alternative approach, still returns model instances
# but limits which fields are fetched from the database
books = Book.objects.only('title', 'price') # only these fields loaded initially
books2 = Book.objects.defer('description') # all fields EXCEPT this one loaded initially| Method | Return | Element type |
|---|---|---|
| Regular QuerySet | पूरा model instance | Model objects |
| values() | Dictionaries | {'field': value} |
| values_list() | Tuples | (value1, value2) |
books = Book.objects.all()
for book in books:
print(book.title, book.get_absolute_url())
book_dicts = Book.objects.values('title', 'price')
for b in book_dicts:
print(b['title'])
book_tuples = Book.objects.values_list('title', 'price')
# flat=True - सिर्फ एक field select करने पर
titles = Book.objects.values_list('title', flat=True)
author_names = Author.objects.values_list('name', flat=True).distinct()
# only() और defer() - अभी भी model instances लौटाते हैं
books = Book.objects.only('title', 'price')
books2 = Book.objects.defer('description')Was this answer clear?