首页 > 解决方案 > 通过对 DRF 中的主模型的单个 GET 请求获取相关模型条目

问题描述

我有一个主模型和六个其他模型,它们是与我的主相关的外键。

我的模型:

#MASTER TABLE
class UserDetails(models.Model):
    user_id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)

#RELATED TABLES
class EducationProfile(models.Model):
    degree_level = models.CharField(max_length=100, null=True, blank=True)
    degree = models.CharField(max_length=100, null=True, blank=True)
    start_date = models.DateField(null=True, blank=True)
    completion_date = models.DateField(null=True, blank=True)
    user = models.ForeignKey(UserDetails, related_name='education')

class AwardsRecognitions(models.Model):
    award_name = models.CharField(max_length=100, null=True, blank=True)
    awarded_by = models.CharField(max_length=100, null=True, blank=True)
    award_date = models.DateField(null=True, blank=True)
    user = models.ForeignKey(UserDetails, related_name='awards')

我正在尝试通过对模型的 GET 请求来获取所有相关模型的信息UserDetails。我试过使用PrimaryKeyRelatedFieldin ,UserDetailsSerializer但这并没有给我预期的输出。结果是嵌套字段中只有相关条目的 id。

我的序列化器:

class UserDetailsSerializer(serializers.ModelSerializer):
    education = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    awards = serializers.PrimaryKeyRelatedField(read_only = True, many = True)

    class Meta:
        model = UserDetails
        fields = '__all__'

class EducationProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = EducationProfile
        fields = '__all__'

class AwardsRecognitionsSerializer(serializers.ModelSerializer):

    class Meta:
        model = AwardsRecognitions
        fields = '__all__'

预期结果

GET 请求格式 - <<UserDetails_model_endpoint>>/<<user_id_primary_key>>/

响应格式 -

{"user_id" : <<user_id>>,
 "first_name" : "foo",
 "last_name" : "bar",
 "education":[{"id":5,
               "degree_level": "xxxx",
               "degree":"xxxx",
               "start_date":"xxxx",
               "completion_date":"xxxx"},
              {"id":7,
               "degree_level": "yyyy",
               "degree":"yyyy",
               "start_date":"yyyy",
               "completion_date":"yyyy"}],
 "awards":[{"id":3,
            "award_name":"nnnn",
            "awarded_by":"nnnn",
            "awarded_date":"nnnn"},
           {"id":7,
            "award_name":"mmm",
            "awarded_by":"mmmm",
            "award_date":"mmmm"}]

请指出我实现这一目标的正确方向,任何想法都会受到赞赏。TIA

标签: django-rest-frameworkdjango-serializer

解决方案


包括您为相关模型而不是主键相关字段创建的模型的序列化程序。顾名思义,PrimaryKeyRelatedField 只会为您提供 JSON 中的主键。

class UserDetailsSerializer(serializers.ModelSerializer):
    education = EducationProfileSerializer(many=True, read_only=True)
    awards = AwardsRecognitionsSerializer(many=True, read_only=True)

    class Meta:
        model = UserDetails
        fields = '__all__'

有关更多详细信息,请查看https://www.django-rest-framework.org/api-guide/relations/#nested-relationships


推荐阅读