首页 > 其他分享 >rdf序列化关联字段

rdf序列化关联字段

时间:2022-12-28 23:33:26浏览次数:44  
标签:customer product name models 关联 ## rdf 序列化 class

## 问题描述

# 序列化方式
class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = "__all__"

## 得到的结果

{
        "id": 1,
        "quantity": 1,
        "amount": 20,
        "buy_time": "2022-12-27T22:48:48.611996+08:00",
        "customer": 1,
        "product": 1
    },

但,我需要得到:外键的关联字段名

# ==》解决方案

## 第一步:新增模型的 @property

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.RESTRICT, verbose_name="客户")
    product = models.ForeignKey(Product, on_delete=models.RESTRICT, verbose_name="产品")
    quantity = models.SmallIntegerField("购买数量")
    amount = models.SmallIntegerField("购买金额")
    buy_time = models.DateTimeField("购买时间", auto_now=True)  # 自动添加时间

    @property
    def customer_name(self):
        return self.customer.name

    @property
    def product_name(self):
        return self.product.name

## 第二步:修改序列化器

class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ("customer_name", "product_name", "quantity", "amount", "buy_time")

## 得到想要的结果

{
        "customer_name": "李雷",
        "product_name": "车蜡",
        "quantity": 1,
        "amount": 20,
        "buy_time": "2022-12-27T22:48:48.611996+08:00"
    },

 

参考资料:https://my.oschina.net/u/4403815/blog/4094252

标签:customer,product,name,models,关联,##,rdf,序列化,class
From: https://www.cnblogs.com/python100/p/17011524.html

相关文章