Skip to content
Advertisement

Serialize a queryset including the ForeignKey values

models.py:

class Project(models.Model):
    project_code = models.CharField(max_length=250, null=False, blank=False)
    description = models.CharField(max_length=1000, null=True, blank=True)


class ProjectManager(models.Model):
    name = models.CharField(max_length=250, null=False, blank=False)
    project_id = models.ForeignKey(
        Project,
        on_delete=models.CASCADE
    )

views.py:

def ajax_search(request):
    if request.method == 'GET':
        category = request.GET['category']
        if category == 'Project':
            result = Project.objects.all()
            data = serialize("json", result, cls=DatetimeJSONEncoder)
            return HttpResponse(data, content_type="application/json")
        else:
            result = ProjectManager.objects.select_related('project_id').all()
            data = serialize("json", result, cls=DatetimeJSONEncoder)
            return HttpResponse(data, content_type="application/json")
        return HttpResponse('')
    return HttpResponse('')

I would like to return a json response with the content of ProjectManager + the content of the Project associated to that ProjectManager (ForeignKey).

According to what I have read in the Django documentation, to do a left join, the best thing to do would be to use select_related.

In fact, it works, but when I serialize ProjectManager, the Project values are not included in the JSON string. How could I put all into the JSON?

Advertisement

Answer

you can create serializers.py file and insert this code there

# import your models
from rest_framework import serializers

class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = "__all__"
        
class ProjectManagerSerializer(serializers.ModelSerializer):
    project_id = ProjectSerializer(many=True)
    class Meta:
        model = ProjectManager
        fields = "__all__"

# views.py
qs = ProjectManager.objects.select_related('project_id').all()
resp = ProjectManagerSerializer(qs, many=True).data
Advertisement