How do I return all foreign key values into a single dict in the Django ORM?
I understand how to access these values in Python, but I’m looking to retrieve them from a dict, rather than a class.
class ChildModel(models.Model):
location = models.TextField()
class MasterModel(models.Model):
town = models.ForeignKey(ChildModel, on_delete=models.CASCADE)
- To access the location in Python:
queryset[0].town.location
- Accessing the values themselves does not return the location field.
queryset.values() = {town: 1}
- What I want is:
queryset.values() = {town: 1, location: some_value}
If I run the SQL query in Postgres I get the dict I’m looking for (all inner join fields returned as a single dict). But how to do this in Django?
2
Answers
you can do so using annotation and F, this is a sample code :
where F helps you reach the value of the child class field.
another way which uses django-rest-framework would be to use serializers which do such thing automatically,
this would be your serializers.py file:
and you this code would display the data:
Simply do this:
You can also use alias