5π
q = B.objects.filter(id=id).values('salary','a__id','a__name','a__age')
this will return a ValuesQuerySet
values(*fields) Returns a ValuesQuerySet β a QuerySet subclass that
returns dictionaries when used as an iterable, rather than
model-instance objects.Each of those dictionaries represents an object, with the keys
corresponding to the attribute names of model objects.
You can actually print q.query
to get the sql query behind the QuerySet
, which in this case is exactly as you requested.
1π
Please try this:
result = B.objects.filter(a__id=1).values('a__id', 'a__name', 'a__age', 'salary')
The result is a <class 'django.db.models.query.ValuesQuerySet'>
, which is essentially a list of dictionaries with key as the field name and value as the actual value. If you want only the values, do this:
result = B.objects.filter(a__id=1).values_list('a__id', 'a__name', 'a__age', 'salary')
The result is a <class 'django.db.models.query.ValuesListQuerySet'>
, and itβs essentially a list of tuples.
- [Django]-How do you decide on creating a new model vs a field in django?
- [Django]-Error in db with modeltranslation in django
- [Django]-TemplateSyntaxError: Could not parse the remainder