如何在Django restframwork中运行我们的函数

时间:2018-02-16 18:05:19

标签: python django model-view-controller django-rest-framework sms-verification

我想运行我的函数来处理对序列化程序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的foreigne键

我想在向用户发送请求时创建url 改了两个表:用户短信

模型:

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)

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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

答案 2 :(得分: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()