S
S
satioidou2se2020-06-12 02:42:47
Django
satioidou2se, 2020-06-12 02:42:47

How to override the save method in a model with a ManyToMany field?

There is a model

class Payment(models.Model):
    order = models.ManyToManyField(TicketPay, verbose_name="Заказ", blank=True, default=None)
    ticket = models.ForeignKey(Ticket, verbose_name="Билет", blank=True, default=1, null=True,
                               on_delete=models.SET_NULL)
    nmb = models.IntegerField("Количество", default=1)
    price_per_item = models.DecimalField("Стоимость", default=0, max_digits=10, decimal_places=2)
    total_price = models.DecimalField("Сумма", default=0, max_digits=10, decimal_places=2)  # price*nmb
    created = models.DateTimeField("Создано", auto_now_add=True, auto_now=False)
    updated = models.DateTimeField("Обновлено", auto_now_add=False, auto_now=True)

    def __str__(self):
        return "%s Билета(ов). В сумме %s RUB" % (self.nmb, int(self.total_price))

    class Meta:
        verbose_name = "Билет в заказе"
        verbose_name_plural = "Билеты в заказе"

    def save(self, *args, **kwargs):
        price_per_item = self.ticket.price
        self.price_per_item = price_per_item

        self.nmb = self.order.count()
        self.total_price = int(self.nmb) * price_per_item

        super(Payment, self).save(*args, **kwargs)

It is necessary that when you select any amount of TicketPay in the order field and a ticket in the ticket field and then save, information is automatically added to the price_per_item fields (this works), nmb (when saving, the error "Payment: 1 Ticket(s) pops up). In total 0 RUB" needs to have a value for field "id" before this many-to-many relationship can be used.") and total_price (this also works with the entered nmb)
Looked at the forums, they say that you need to save the ManyToMany field with the .save method so that such an error does not pop up.The
question is how to do this?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question