生成密钥并将其保存到Model Django Rest Framework

时间:2018-10-25 09:09:27

标签: django-rest-framework

  

models.py

from django.db import models

class UserProfile(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

class = SecretKey(models.Model):
   key = models.CharField(max_length=50, unique = True)
   owner = models.ForeignKey(UserProfile, on_delete = models.CASCADE)
  

views.py

from .serializers import UserProfileSerializer, KeySerializer
from rest_framework.response import Response
from .models import UserProfile, SecretKey
from rest_framework import viewsets

class ProfileAPIView(viewsets.ModelViewSet):

    serializer_class = UserProfileSerializer
    queryset = UserProfile.objects.all()

class GenerateSecretKeyAPIView(viewsets.ModelViewSet):
    serializer_class = KeySerializer
    queryset = SecretKey.objects.all()
  

serializers.py

class KeySerializer(serializers.ModelSerializer):
class Meta:
    model = SecretKey
    fields = ('key','owner')
  

urls.py

from django.urls import path
from rest_framework import routers
from .views import ProfileAPIView, GenerateSecretKeyAPIView

router = routers.DefaultRouter()

router.register('stud',StudentProfileAPIView,base_name='stud-prof-api-view'),
router.register('key',GenerateSecretKeyAPIView,base_name='key-gen-api-view'),
urlpatterns = router.urls

这是我的api的简短描述。现在,当我从前端调用POST请求时,该请求包含一个数字(n)和所有者的ID。我想创建一个长度为n的随机数,并将密钥保存到{{1 }}字段和所有者ID放入key模型的owner字段

请帮助 在此先感谢

1 个答案:

答案 0 :(得分:0)

我认为您可以执行以下操作:

class = SecretKey(models.Model):
    key = models.CharField(max_length=50, unique = True)
    owner = models.ForeignKey(UserProfile, on_delete = models.CASCADE)

    def generate_key(self):
        key = ''.join(random.choice('0123456789') for x in range(8))

        if SecretKey.objects.filter(key=key).exists():
            return self.generate_key()

        return key

    def save(self, *args, **kwargs):
        if not self.key:
            self.key = self.generate_key()

        return super(SecretKey, self).save(*args, **kwargs)