如何在django中制作可以区分put和post方法的信号?

时间:2016-12-30 12:45:01

标签: python django django-rest-framework django-signals

我正在使用in_built Django用户,并希望为每个添加的用户生成通知,但我不希望在put请求上生成通知。它应该只在post请求时生成。 我的模特是......

Models.py

class User(AbstractUser):
    gender= models.CharField(choices=GENDER, max_length=10, null=True, blank=True)
    role= models.CharField(choices=ROLE_CHOICE, max_length=15, null=True, blank=True)
    designation=models.CharField(max_length=225,null=True,blank=True)
    employee_id = models.CharField(max_length=20, default=None, null=True)

class Notification(models.Model):
    text = models.CharField(max_length=225)
    recipient=models.ForeignKey(User,related_name='notification')
    timestamp = models.DateTimeField(null=True,blank=True,auto_now_add=True)
    unread = models.BooleanField(default=True, blank=False)
    send_by= models.ForeignKey(User, null=True,blank=True, related_name='Notification')

并且在我的信号中我做了...... ....

Signals.py

@receiver(post_save, sender= Any_model)
def comment_recieved(sender,**kwargs):
    obj= kwargs.get('instance')
        recipient=User.objects.get(is_superuser=True)
        Notification.objects.create(
            recipient= recipient,
            comment= obj,
            project=obj.project,
            type="commented",
            send_by=obj.supporter,
            text= "%s has commented on %s" % (obj.supporter, obj.project)
        )
        return None

现在的问题是,每次执行put或post请求时,它都会保存用户实例,因此会创建Notification对象。我只想在创建新用户时创建Notification。

2 个答案:

答案 0 :(得分:1)

假设您使用序列化程序进行DRF视图,以便覆盖用户序列化程序的create()方法。

class UserSerializer(serializer.ModelSerializer):
    ...
    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        Notification.objects.create( # fill your fields here )
        return user

但更明确的解决方案是编写自定义管理器并覆盖create方法,该方法将接受UserNotification模型的两个字段:

class UserManager(models.Manager):
    ...
    def create(self, gender, role ... type #and so on):
        user = User(
            gender=gender
            role=role
            ...
            # other fields               
            )
        user.save()
        notification = Notification(
                           type=type 
                           ..  
                           # other fields
                           )      
        notification.save()         
        return user

class User(models.Model):
    ....
    objects = UserManager()

序列化器:

    class UserSerializer(serializer.ModelSerializer):
        ...
        def create(self, validated_data):
            return User.objects.create(
                   gender=validated_data.get('gender')
                   role=validated_data.get('role')
                   ....
                   type = validated_data.get('type')

答案 1 :(得分:1)

post_save信号发送一个名为created的参数

  

布尔值;如果创建了新记录,则为True。

您可以使用它来区分是创建新记录还是仅更新。

More info in the docs