Search code examples
djangodjango-modelsdjango-rest-frameworkfetchdjango-queryset

How to replace foreign key by its associated value in django queryset


I'm fairly new to django and i would need your help!

I wrote an api/route view that query the database and return a JSON to my fetch function in my javascript.

Is there a way to query the database and got back a queryset with foreign key replaced by its associated value ?

I though i could use ModelName.objects.select_related( 'field ') but i didn't understand how it works. If you have a solution or advices on better way to achieve the goal, Thanks in advance!

Context in pseudo-code:

// HTML //

  • Button onclick function get_list_of_data

// JS //

function get_list_of_data:

  • Fetch URL of route django

  • Convert response to JSON

  • iterating through JSON to fill HTLM div

// Django //

  • use ModelName.objects.filter( name = name ) to get list of data in Queryset

  • use serializers.serialize(json, ...") to get JSON from Queryset

  • return JsonResponse (json_query)


Solution

  • If I understood the problem well, when you serialize a model that has a ForeignKey field defined you get only the id value in JSON response but you would like to get the whole object (not only a number) returned.
    The way to do that is to specifically write serializer for that ForeignKey model and then use it within the serializer od the model that you are trying to fetch.
    You haven't provided any code, but here is some example that might help you:

    class SecondModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = SecondModel
            fields = '__all__'
    
    
    class FirstModelSerializer(serializers.ModelSerializer):
        foreign_key_field = SecondModelSerializer()
    
        class Meta:
            model = FirstModel
            fields = ('id', 'foreign_key_field', 'field1', 'field2')
    

    Here in your FirstModelSerializer you specifically told Django to use SecondModelSerializer for your ForeignKey field (I named it foreign_key_field). This way Django will know how to serialize that field instead of returning only the id value.