0

我正在尝试创建一个通知系统来跟踪我的用户的所有活动。为了实现这一点,我创建了两个模型,贡献模型和通知模型

class Contribution(models.Model):
    slug            =   models.SlugField(unique=True, blank=True, null=True)
    user            =   models.ForeignKey(User, on_delete=models.PROTECT)
    amount          =   models.DecimalField(default=0.00, max_digits=6, decimal_places=2)
    zanaco_id       =   models.CharField(max_length=20, blank=True, unique=True, null=True)

class Notification(models.Model):
    slug        =   models.SlugField(unique=True, blank=True)
    content_type    =   models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id       =   models.PositiveIntegerField()
    content_object  =   GenericForeignKey('content_type', 'object_id')
    message         =   models.TextField(null=True)

每次用户在 Contribution 表中创建对象时,我都想创建一个 Notification 对象,但是在获取从 CreateView 创建的对象时遇到了一些困难

class ContributionAdd(CreateView):
    model           =   Contribution
    fields          = ['user', 'amount', 'zanaco_id']
    template_name   =   'contribution_add.html'


    def form_valid(self, form, *args, **kwargs):
        activity_ct = ContentType.objects.get_for_model("????")
        Notification.objects.create(content_type=activity_ct, object_id="?????",content_object=???,)
        return super().form_valid(form)

我怎样才能完成上述任务?他们是使用 mixins 的一种方式吗?

4

2 回答 2

2

该对象是在 superform_valid方法中创建的,因此在调用之前您无法访问它。而是首先调用 super 方法并使用self.object来引用创建的对象:

class ContributionAdd(CreateView):
    model           =   Contribution
    fields          = ['user', 'amount', 'zanaco_id']
    template_name   =   'contribution_add.html'


    def form_valid(self, form):
        response = super().form_valid(form) # call super first
        Notification.objects.create(content_object=self.object) # Why even pass the other values just pass `content_object` only
        return response
于 2021-04-25T10:32:47.280 回答
1

一种优雅的方法是使用后保存信号:

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

@receiver(post_save, sender=Contribution)
def createNotification(sender, instance, created, **kwargs):
    if created:
        Notification.objects.create(content_type=activity_ct, object_id="?????",content_object=???,)
于 2021-04-25T11:06:59.140 回答