[Django]-Django one to one relation queryset

5πŸ‘

βœ…

q = B.objects.filter(id=id).values('salary','a__id','a__name','a__age')

this will return a ValuesQuerySet

values

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.

πŸ‘€zxzak

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.

πŸ‘€Shang Wang

Leave a comment