序列化包含 ForeignKey 值的查询集

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('')

我想 return 一个 json 响应,其中包含 ProjectManager 的内容 + 与 ProjectManager 关联的 Project 的内容(ForeignKey).

根据我在 Django 文档中阅读的内容,要进行左连接,最好的办法是使用 select_related.

事实上,它有效,但是当我序列化 ProjectManager 时,Project 值不包含在 JSON 字符串中。我怎么能把所有的都放进JSON?

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