Django 含有外键模型新增数据以及序列化

Django 原生实现外键

class AppleModel(models.Model):
    id=models.AutoField(primary_key=True)
    app_name=models.CharField(max_length=50)

class PickleModel(models.Model):
    pid=models.AutoField(primary_key=True)
    app=models.ForeignKey(to="AppleModel",on_delete=models.CASCADE,related_name="app")
    color=models.CharField(max_length=20)

python manage.py shell 

app=AppleModel(app_name="iphone")
pickle=PickleModel(app=app,color="red")

 

 

DRF 实现:

class SerApple(serializers.ModelSerializer):

    class Meta:
        model=AppleModel
        fields = "__all__"

class SerPickle(serializers.ModelSerializer):
    class Meta:
        model=PickleModel
        fields = "__all__"

 

由于主表是Apple ,从表是Pickle,所以必须先创建主表,从表由于包含外键,所以如果先创建从表时会报错 "无效主键 “1” - 对象不存在。":

 

 

 

所以外键序列化就需要先序列化主表:

 

 

 

 

 现在需求查询pickle表时想展示对应的外键的app的中文名称在返回响应里,而不是id

需要操刀修改序SerPickle列化器了:

修改后如下:

class SerApple(serializers.ModelSerializer):

    class Meta:
        model=AppleModel
        fields = "__all__"

class SerPickle(serializers.ModelSerializer):
    # source 格式Pickle模型外键模型字段名.主表的字段属性
    app_name=serializers.CharField(source="app.app_name",read_only=True)
    class Meta:
        model=PickleModel
        # fields = "__all__"
        fields = ['app',"color","app_name"]

 

 

posted @ 2020-11-26 16:18  不带R的墨菲特  阅读(1239)  评论(0编辑  收藏  举报