模型类
class Tobacco(models.Model):
product_name = models.CharField(max_length=78, verbose_name="烟草名称", help_text="烟草名称")
number = models.IntegerField(verbose_name="货物数量", help_text="货物数量")
price = models.IntegerField(verbose_name="货物价格", help_text="货物价格")
old_price = models.IntegerField(verbose_name="货物旧价格", help_text="货物旧价格")
factory_simple_name = models.CharField(max_length=32, verbose_name="所属公司", help_text="所属公司")
charge = models.ForeignKey(TobaccoCharge, on_delete=models.CASCADE)
brand_name = models.CharField(max_length=32, verbose_name="业态", help_text="业态")
create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间", help_text="创建时间")
update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间", help_text="更新时间")
class Meta:
db_table = "tobacco"
app_label = "goods"
def __str__(self):
return self.product_name
序列化类
class SerTobacco(serializers.ModelSerializer):
prduct_name_num = serializers.SerializerMethodField()
class Meta:
model = Tobacco
fields = ["id", "product_name", "number", "prduct_name_num"]
def get_prduct_name_num(self, obj):
return obj.product_name + f"的数量是{str(obj.number)}"
view视图
class SearchTobaccoList(APIView):
"""
列表查询
"""
def get(self, request, *args, **kwargs):
all_data = Tobacco.objects.all()
ser = SerTobacco(instance=all_data, many=True)
return Response(ser.data)
返回值
[
{
"id": 1,
"product_name": "黄金叶(天叶中支)",
"number": 493,
"prduct_name_num": "黄金叶(天叶中支)的数量是493"
},
{
"id": 2,
"product_name": "黄鹤楼(1916中支)",
"number": 441,
"prduct_name_num": "黄鹤楼(1916中支)的数量是441"
}
]