简体   繁体   English

在Django Rest Framework中序列化相关模型

[英]Serialize related models in Django Rest Framework

I have django models that are simplified as: 我有django模型,简化为:

class Client(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name


class ClientDetail(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    business_format = models.CharField(max_length=255)


    def __str__(self):
        return "Details for {}".format(self.client.name)


class ClientAssignment(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE)


    def __str__(self):
        return "Assignment: {} for Client: {}".format(self.assignment.name, self.client.name)

class Assignment(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

I am using django-rest-framework and would like to create a view where I can provide client_id and receive a serialized object that contains all 3 related models. 我正在使用django-rest-framework并且想创建一个视图,我可以在其中提供client_id并接收包含所有3个相关模型的序列化对象。 I tried using PrimaryKeyRelatedField as follows but I'm not sure if I'm using this correctly. 我尝试使用PrimaryKeyRelatedField如下,但我不确定我是否正确使用它。

class CompleteClientObject(ModelSerializer):
    assignment = PrimaryKeyRelatedField(many=True, queryset=ClientAssignment.objects)
    detail = PrimaryKeyRelatedField(many=True, queryset=ClientDetail.objects)
    client = PrimaryKeyRelatedField(queryset=Client)

    class Meta:
        model = Client
        fields = ("id", "name", "detail", "assignment",)

How can I achieve this using serializers? 如何使用序列化器实现此目的?

In your serializer fields you can use the source argument to specify a field on the model. 在序列化程序字段中,您可以使用source参数指定模型上的字段。 If you're trying to access the reverse relation from the Client model you should be using the MODELNAME_set field on as your source. 如果您尝试从客户端模型访问反向关系,则应使用MODELNAME_set字段作为源。 This field is added to the other end of a ForeignKey by Django. Django将此字段添加到ForeignKey的另一端。 Ie

assignment = PrimaryKeyRelatedField(
    source='clientassignment_set',
    many=True,
    read_only=True,
)

Note that with read_only=True you don't need to specify a queryset either. 请注意,使用read_only=True您也不需要指定查询集。

Your other choice would be to specify a related_name field on your ForeignKey's which overrides the MODELNAME_set auto-generated fields, and set these to "assignment" and "detail". 您的其他选择是指定一个related_name将覆盖你的ForeignKey的场上MODELNAME_set自动生成的领域,而这些设置为“分配”和“细节”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM