0

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.

1

1 Answer 1

1

There are several ways to do it:

  • You could use nested serializer to render the source field
  • You could start from a Product ModelSerializer where you override the to_representation in order to generate and return the source content
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.