skip to Main Content

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


  1. you can do so using annotation and F, this is a sample code :

    from django.db.models import F
    items = MasterModel.objects.select_related('town').annotate(child_location=F('town__location'))
    
    for item in items:
        print(f"MasterModel: {item.town_id}, Child Location: {item.child_location}")
    

    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:

    class ChildModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = ChildModel
            fields = '__all__'
    
    class MasterModelSerializer(serializers.ModelSerializer):
        town_location = serializers.CharField(source='town.location', read_only=True)
    
        class Meta:
            model = MasterModel
            fields = ['id', 'town', 'town_location']
    

    and you this code would display the data:

    data = MasterModel.objects.all()
    serializer = MasterModelSerializer(data, many=True)
    print(serializer.data[0])
    
    Login or Signup to reply.
  2. Simply do this:

    items = MasterModel.objects.values('town_id', 'town__location')
    

    You can also use alias

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search