如何在Django应用中正确连接Signals到我的Model?

brccelvz  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(195)

我尝试在我的Django应用程序中将Signals 'post_保存'方法连接到这个Order模型:

from django.conf import settings
from django.db import models

from CFTrade.models import Item

    class Order(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_user')
        full_name = models.CharField(max_length=50)
        address1 = models.CharField(max_length=250)
        address2 = models.CharField(max_length=250)
        city = models.CharField(max_length=100)
        phone = models.CharField(max_length=100)
        post_code = models.CharField(max_length=20)
        created = models.DateTimeField(auto_now_add=True)
        edited = models.DateTimeField(auto_now=True)
        total_paid = models.DecimalField(max_digits=7, decimal_places=2)
        order_key = models.CharField(max_length=200)
        billing_status = models.BooleanField(default=False)
    
        class Meta:
            ordering = ('-created',)
        
        def __str__(self):
            return str(self.created)

同时还进口了信号接收模块:在我的应用的apps.py文件中

from django.apps import AppConfig

class OrdersConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'orders'

    def ready(self):
        import orders.signals

在我的Model处理器中,我没有收到我需要的model信息,包括billing_statuscreated`

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

@receiver(post_save, sender=Order)
def inventory_handler(sender, instance, created, *args, **kwargs):
    print('First step')
    print(args, kwargs)`

以下是我得到的:First step () {'signal': <django.db.models.signals.ModelSignal object at 0x0000026212438590>, 'update_fields': None, 'raw': False, 'using': 'default'}我该如何解决这个问题?

svujldwt

svujldwt1#

它在示例中,因此:

@receiver(post_save, sender=Order)
def inventory_handler(sender, instance, created, *args, **kwargs):
    print('First step')
    print(instance.billing_status)
    print(created)

这里的argskwargs只捕获 other 参数,因此不是senderinstancecreated

相关问题