我正在用django-rest-framework为online-store创建API,但由于某种原因,我的post_保存信号无法正常工作。这个想法是:我有一个模型Product
和类别。Product
模型有一个名为in_stock
的字段,默认为True
。至于模型Category
,它也有字段in_stock
,但这里是False
。创建产品示例时,我想使用信号将Category
字段in_stock
分配给True
值。下面是模型的代码:
class Category(models.Model):
category_name = models.CharField(max_length=255, verbose_name='Категория')
description = models.TextField(verbose_name='Описание')
in_stock = models.BooleanField(default=False, verbose_name='В наличии')
slug = models.SlugField()
image_url = models.ImageField(upload_to='categories/uploads/%Y/%m/%d/', null=True, blank=True,
default='media/images.png', verbose_name='Изображение')
parent = models.ForeignKey('self', on_delete=models.PROTECT, related_name='children', null=True, blank=True,
verbose_name='Родительская категория')
def __str__(self):
return f'{self.parent}, {self.category_name}'
class Product(models.Model):
product_name = models.CharField(max_length=255, verbose_name='Товар')
description = models.TextField(verbose_name='Описание')
price = models.IntegerField(verbose_name='Цена')
discount_percent = models.IntegerField(default=0, verbose_name='Процент скидки')
in_stock = models.BooleanField(default=True, verbose_name='В наличии')
amount = models.IntegerField(verbose_name='Количество')
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, verbose_name='Поставщик')
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория')
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, verbose_name='Бренд')
image = models.ForeignKey(ProductImage, on_delete=models.SET_DEFAULT, default=1,
verbose_name='Изображение')
以下是信号:
@receiver(post_save, sender=Product)
def update_category_is_active(sender, instance, created, **kwargs):
print(instance)
if created and instance.in_stock:
instance.category.in_stock = True
instance.category.save()
2条答案
按热度按时间bnl4lu3b1#
您可以通过重写
save()
方法来获取它,而不使用信号drkbr07n2#
是否在
apps.py
文件中添加了就绪函数?这是必需的,因为Django应该知道哪些文件有额外的代码(如pre_保存/ post_save),这些代码应该在服务器运行时执行。它看起来像这样: