0

我想运行我的函数在对序列化程序的 url 的请求中做一些事情

我的序列化器:

class usersSerializer(ModelSerializer):
    class Meta:
        model=users
        fields="__all__"    

我对序列化程序的看法:

class usersCreate(generics.CreateAPIView):
    queryset=users.objects.all()
    serializer_class=usersSerializer

我的功能:

def f():
    now=datetime.now()
    now10=now + timedelta(minutes = 10)
    quer=users.objects.last()
    rcode=randint(1000,9999)
    a=SMS(users_id=quer,code=rcode,expireTime=now10)
    a.save()

SMS是另一个表users_id ====>用户表中id的外键

我想当我向用户发送请求时创建 url 更改了两个表:用户 SMS

楷模:

class users(models.Model):
    number=models.CharField(verbose_name="userNumber",max_length=11)
    name=models.CharField(verbose_name="name",max_length=40)
    createTime=models.DateTimeField( auto_now_add=True,auto_now=False)
    status=models.BooleanField(default=False)

class SMS(models.Model):
    users_id=models.ForeignKey(users,on_delete=models.CASCADE,default=0)
    code=models.PositiveSmallIntegerField(verbose_name="randomCode")
    expireTime=models.DateTimeField()
    status=models.BooleanField(default=False)
4

3 回答 3

2

在 models.py 上,您可以使用信号。这比假设 LAST 将返回当前用户的 SMS 消息更安全。

from django.db.models.signals import post_save,pre_save

@receiver(post_save, sender=users)
def post_save_users(sender, instance, created, **kwargs):
    if created:
        now=datetime.now()
        now10=now + timedelta(minutes = 10)
        quer=users.objects.last()
        rcode=randint(1000,9999)
        sms = SMS(user_id=instance,code=rcode,expireTime=now10)
        sms.save()
    instance.save()
于 2018-02-16T18:22:20.737 回答
1

您可以覆盖 CreateAPIView 的 create 方法。f创建模型后调用。

class usersCreate(generics.CreateAPIView):
    queryset=users.objects.all()
    serializer_class=usersSerializer

    def create(self, request, *args, **kwargs):
        r = super(usersCreate, self).create(request, *args, **kwargs)
        f()
        return r
于 2018-02-16T18:15:10.803 回答
0
@receiver(post_save,sender=users)
def post_save_users(sender, instance, created, **kwargs):
    if created:
        now=datetime.now()
        now10=now + timedelta(minutes = 10)
        quer=users.objects.last()
        rcode=randint(1000,9999)
        a=SMS(users_id=instance,code=rcode,expireTime=now10)
        a.save()
于 2018-02-17T16:05:51.297 回答