I'm Building project for practice and i have a product and i want to show to everyone all the names of users that selling this product. I've set the user field as ForeignKey of User in models,but I'm getting in the response object only the id of the user without anything else. What is the correct way to access the user name?
The model of the product sellers:
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)
The view:
@api_view(['GET'])
def getSellersById(request,pk):
sellers=ProductSeller.objects.filter(product_id=pk)
seralizer=SellersSerializer(sellers,many=True)
return Response(seralizer.data)
The response object:
{
"id": 2,
"condition": "Almost new",
"asked_price": 50,
"image": "image.jpg",
"product_id": 8,
"user": 1
},
The wanted result:
{
"id": 2,
"condition": "Almost new",
"asked_price": 50,
"image": "image.jpg",
"product_id": 8,
"user": 1,
"seller_name":"John"
},
CodePudding user response:
You can add a method to Product
model:
Product(...):
...
def get_all_users_selling(self):
return User.objects.filter(productseller_set__product_id=self)
After that add it to the serializer's response:
@api_view(['GET'])
def getSellersById(request,pk):
sellers=ProductSeller.objects.filter(product_id=pk)
seralizer=SellersSerializer(sellers,many=True)
for seller in seralizer.data:
seller["all_users"] = [user.username for user in Product.objects.get(seller.get("product_id")).get_all_users_selling()]
return Response(seralizer.data)
Also, don't use _id
in the end of ForeignKey
field variable, it's confusing, because Django creates column with _id
suffix, so it becomes something_id_id
.
CodePudding user response:
I solved it by adding the sellerSerializer class a method that give me the seller name:
class SellersSerializer(serializers.ModelSerializer):
seller_name=serializers.SerializerMethodField(read_only=True)
class Meta:
model=ProductSeller
fields='__all__'
def get_seller_name(self,obj):
return str(obj)