#Implementing generics.ListCreateAPIView using a serializer on a model with many to many relationship

2 messages · Page 1 of 1 (latest)

junior slate
#

I have models defined as:


class FoodItem(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    def __str__(self) -> str:
        return self.name
    
class Order(models.Model):
    table_number = models.IntegerField()
    customer_name = models.CharField(max_length=255)
    food_items = models.ManyToManyField(FoodItem, through='OrderItem')
   
    total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    timestamp = models.DateTimeField(auto_now_add=True)

    def calculate_total_price(self, food_items):
        # Calculate the total price by summing up subtotals of all order items
        total_price = sum(item.subtotal for item in self.orderitem_set.all())
        self.total_price = total_price
        self.save()
        return total_price

    def get_food_items(self):
        # Return the related food items
        return self.food_items.all()

    def __int__(self):
        return self.table_number

class OrderItem(models.Model):
    order= models.ForeignKey(Order, on_delete=models.CASCADE)
    food_item = models.ForeignKey(FoodItem, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=2)
    subtotal = models.DecimalField(max_digits=8, decimal_places=2, default=0)
    
    def save(self, *args, **kwargs):
        # Calculate subtotal before saving
        self.subtotal = self.quantity * self.price
        super().save(*args, **kwargs)
  
    def __str__(self):
      return f"{self.quantity} x {self.food_item.name} in Order {str(self.order.id)}"

I need help in implementing serializers on a model with many to many field and then writing generics.ListCreateAPIView

severe brookBOT
#

Hi. You'll find people are more willing to help if you provide some details about your problem. A good starting point is answering what are you trying to do, what you expect to happen and what actually happened. If your answers are something like "Login to the site. To be logged in. It doesn't work", you're not providing enough detail. If you have an error, include the full error message and the traceback. For a more thorough discussion on how to ask good technical questions see:

https://www.freecodecamp.org/news/how-to-ask-good-technical-questions/