【发布时间】:2022-10-02 14:49:20
【问题描述】:
我正在为实践构建项目,并且我有一个产品,我想向所有人展示销售该产品的所有用户的姓名。 我在模型中将用户字段设置为用户的 ForeignKey,但我在响应对象中只获取用户的 id 而没有其他任何内容。访问用户名的正确方法是什么?
产品卖家的型号:
class ProductSeller(models.Model):
product_id=models.ForeignKey(Product,on_delete=models.CASCADE,default = None)
user=models.ForeignKey(User,on_delete=models.CASCADE)
condition = models.CharField(max_length=100, choices=condition_choices)
asked_price=models.IntegerField()
image=models.ImageField(null=True,blank=True)
风景:
@api_view([\'GET\'])
def getSellersById(request,pk):
sellers=ProductSeller.objects.filter(product_id=pk)
seralizer=SellersSerializer(sellers,many=True)
return Response(seralizer.data)
响应对象:
{
\"id\": 2,
\"condition\": \"Almost new\",
\"asked_price\": 50,
\"image\": \"image.jpg\",
\"product_id\": 8,
\"user\": 1
},
想要的结果:
{
\"id\": 2,
\"condition\": \"Almost new\",
\"asked_price\": 50,
\"image\": \"image.jpg\",
\"product_id\": 8,
\"user\": 1,
\"seller_name\":\"John\"
},
标签: python django django-models django-rest-framework