Django信号post_保存方法

owfi6suc  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(145)

我正在用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()
bnl4lu3b

bnl4lu3b1#

您可以通过重写save()方法来获取它,而不使用信号

class Product(models.Model):
    ...

    def save(self, *args, **kwargs):
        if self.pk is None:
            if self.in_stock:
                self.category.in_stock = True
                self.category.save()
        super().save(*args, **kwargs)
drkbr07n

drkbr07n2#

是否在apps.py文件中添加了就绪函数?这是必需的,因为Django应该知道哪些文件有额外的代码(如pre_保存/ post_save),这些代码应该在服务器运行时执行。
它看起来像这样:

from django.apps import AppConfig

class AppNameConfig(AppConfig):
    name = 'appname'

    def ready(self):
        import appname.signals

相关问题