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

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")

另外一个例子,测试没问题的

class Merchant(models.Model):
    name = models.CharField(max_length=200, verbose_name='商家名称', null=False)
    address = models.CharField(max_length=200, verbose_name='商家地址', null=False)
    logo = models.CharField(max_length=200, verbose_name='商家logo', null=False)

class GoodsCategory(models.Model):
    name = models.CharField(max_length=20, verbose_name='分类名称')
    merchant = models.ForeignKey(Merchant, on_delete=models.CASCADE)

python manage.py shell
>>> merchant1=Merchant.objects.get(pk=45)
>>> GoodsCategory.objects.create(name="独特夜宵",merchant=merchant1)
<GoodsCategory: GoodsCategory object (324)>

DRF 实现:

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

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

img

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

img

img

现在需求查询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"]

 

img

posted @ 2023-12-09 10:47  坚强的小蚂蚁  阅读(181)  评论(0编辑  收藏  举报