I'm Trying to send data about all the available retailers and their prices for a particular product . How should I approach creating the view for it?
Here are my models:
class Product(models.Model):
name = models.CharField(max_length=30,null=True,blank=True)
brand = models.CharField(max_length=20,null=True,blank=True)
image = models.ImageField(null=True,blank=True)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return self.name
class Retailer(models.Model):
name = models.CharField(max_length=20,null=True,blank=True)
image = models.ImageField(null=True,blank=True)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return self.name
class RetailerProduct(models.Model):
url = models.CharField(max_length=300,null=True,blank=True)
price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True)
difference = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True)
retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE)
available = models.BooleanField(default=False)
_id = models.AutoField(primary_key=True, editable=False)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
def __str__(self):
return self.retailer.name + " - " + self.product.name
Here is the JSON data I would like to send.
{
'_id': '2',
'name': 'ProductName',
'image': '/images/ProductName.jpg',
'description':'',
'brand': 'brandname',
'category': 'categoryname',
'price': 599.99,
'Instock': False,
'ranking': 10,
'numSources': 4,
'sources':[{'Retailer':'Amazon', 'Price':'799.99'}, {'Retailer':'Onbuy', 'Price':'599.99'}, {'Retailer':'Ebay', 'Price':'599.99'}, {'Retailer':'NewEgg', 'Price':'499.99'}],
},
Here Is my current view for getting a specific product:
class getProduct(APIView):
def get(self, request,pk):
product = Product.objects.get(_id=pk)
serializer = ProductSerializer(product,many=False)
return Response(serializer.data)
The serializer just has field = '__all__'
Any help would be much appreciated.
There are several ways to do it:
source
fieldProduct ModelSerializer
where you override the to_representation
in order to generate and return the source
content
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.