How do I populate my OrderItem model with fields from my Product model in Django?

  django, python

I am using ModelViewSet and serializers to view my orders and products.
So in my admin panel for my Product model I already added product, price, and price per pound. So eg. (banana, 2.00, 2.99).

class Product(models.Model):
    name = models.CharField(max_length=70)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    price_per_pound = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    category = models.ForeignKey(Categories, related_name='products', on_delete=models.CASCADE)

    def __str__(self):
        return self.name

In my OrderItem model I can select the product that is available, but when I select the banana I want the price and price_per_pound fields to auto populate with what I have in my Product model eg.(2.00, 2.99). How would I go about this?

class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
    product = models.ForeignKey(Product, related_name='+', on_delete=models.CASCADE)
    price = models.DecimalField(Product.price) //Tried this way, but doesn't work.
    price_per_pound = models.ForeignKey(Product, related_name='product_price_per_pound', on_delete=models.CASCADE) //this still only give me the field names of my product
    quantity = models.PositiveIntegerField(default=1)
    ready = 1
    on_its_way = 2
    delivered = 3
    STATUS_CHOICES = (
        (ready, 'ready'),
        (on_its_way, 'on its way'),
        (delivered, 'delivered'),
    )
    status = models.SmallIntegerField(choices=STATUS_CHOICES)

Source: Python Questions

LEAVE A COMMENT