Django error: save() got an unexpected keyword argument 'toppings'

Django error: save() got an unexpected keyword argument 'toppings'

在管理员 UI 上,填写字段并按下 'save' 按钮后,出现此错误 谁能告诉我问题出在哪里?据我了解,此问题通常是由于未放置此行代码super(Pizza, self).save(*args, **kwargs)引起的,但我仍然出现此错误并且无法理解为什么

仅供参考:我想让每个 Pizza 都有一个默认的 Cheese Topping,这适用于所有 Pizza,它不应该能够删除它

class Topping(models.Model):                                                                                         
    name = models.CharField(max_length=64)                                                                           

    def __str__(self):                                                                                               
        return(f"{self.name}")                                                                                       


class Pizza(models.Model):                                                                                           
    PIZZA_SIZES = (                                                                                                  
        ('S', 'Small'),                                                                                              
        ('L', 'Large'),                                                                                              
    )                                                                                                                

    pizza_type = models.CharField(max_length=64)                                                                     
    pizza_size = models.CharField(max_length=1, choices=PIZZA_SIZES)                                                 
    qty_toppings = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3)], default=0)           
    toppings = models.ManyToManyField(Topping)                                                                       
    price = models.IntegerField(help_text="Price in $")                                                              


    def __str__(self):                                                                                               
        return f"Size: {self.get_pizza_size_display()}, Type: {self.pizza_type}, Number of Toppings: {self.qty_toppi\
ngs},  Price: {self.price}, Toppings: {self.toppings.in_bulk()}"                                                     

    def save(self, *args, **kwargs):                                                                                 
        # if 'toppings' not in kwargs:                                                                               
        # kwargs.setdefault('force_insert', True)                                                                    
        # kwargs.setdefault('force_update', True)                                                                    
        kwargs.setdefault('toppings', Topping.objects.get(name='Cheese'))                                            
        super(Pizza, self).save(*args, **kwargs) 

您无法在保存前通过 M2M 对象添加相关的记录。阅读 this doc 关于 M2M 的内容。

您可以按照评论中的建议进行操作:

def save(self, *args, **kwargs):                                                                                                                                                                                          
    super(Pizza, self).save(*args, **kwargs)
    self.toppings.add(Topping.objects.get(name='Cheese'))

或者你可以设置post_save信号:

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Pizza)
def update_stock(sender, instance, **kwargs):
    instance.toppings.add(Topping.objects.get(name='Cheese'))