Django models, deserialize PrimaryKeyRelatedField

时间:2017-06-09 12:52:53

标签: django django-models django-serializer

I have a microservice application, which needs to pass an object from service to service, and the receiver needs to save that object to the db. The object I am trying to pass has a field which is a foreign key to another table. That is:

class RelatedModel(models.Model):
    id=models.CharField(max_length=3, primary_key=True)
    name=models.CharField(max_length=30)

class PrimaryModel(models.Model): id=models.IntegerField(primary_key=True) rel_model=models.ForeignKey(RelatedModel)

class RelatedSerializer(serializers.ModelSerializer): class Meta: fields = 'all' model = RelatedModel

class PrimarySerializer(serializers.ModelSerializer): rel_model = RelatedSerializer()

class Meta:
    fields = '__all__'
    model = PrimaryModel

However, in this case, the serializer on the receiving end was invalid, saying that the related model already existed in the db.

I tried using PrimaryKeyRelatedField, but then the receiving serializer does not contain the rel_model at all.

How can I deserialize the related field in the receiving serializer?

1 个答案:

答案 0 :(得分:0)

您是否尝试使用此类序列化工具

class RelatedSerializer(serializers.ModelSerializer): 
    class Meta:
        model = RelatedModel
        fields = ('name', )

class PrimarySerializer(serializers.ModelSerializer): 
    rel_model = RelatedSerializer()
    class Meta: 
        model = PrimaryModel 
        fields = ('rel_model', )

通过序列化程序发布数据时,id无法传递,因为它是主键字段。