我是Django和Django Rest Framework的新手,所以我需要一些帮助。
我想从Django模型中接收时间数据。如果没有为特定用户存储时间,则应创建该时间,将其保存在我的模型中并返回该时间数据。我还使用Simple-JWT进行令牌身份验证,这意味着没有有效令牌就无法访问数据库。
到目前为止,这是我的代码:
models.py:
class Mymodel(models.Model):
emp= models.ForeignKey(User, on_delete = models.CASCADE)
time = models.DateTimeField()
views.py:
def get_time(request):
if (request.method == 'GET'):
tk = request.GET.get('token') #token stored in LocalStorage
headers = {'Authorization': 'Bearer ' + tk}
url = 'http://127.0.0.1:8000/my_api/'
response = requests.get(url, headers)
if response:
user_id = User.objects.get(username=request.GET.get('username')).pk
user = User.objects.get(id = user_id)
if not Mymodel.objects.filter(emp=user).exists():
current_time = timezone.now()
create_time = Mymodel.objects.create(emp=user, time=current_time)
data = create_time.time
return HttpResponse(data)
class MyAPI(generics.ListAPIView):
permission_classes = [IsAuthenticated] #need to pass in JWT token in order to access the model.
serializer = MySerializer
def get_queryset(self):
user_id = User.objects.get(username=request.GET.get('username')).pk
user = User.objects.get(id = user_id)
user_data = Mymodel.objects.all()
queryset = user_data.filter(id=user_id)
return queryset
serializers.py:
class MySerializer(serializers.ModelSerializer):
class Meta:
model = Mymodel
fields = ('time')
我只想从表中读取并检查用户是否有时间。如果没有,它应该在模型中创建时间。但是,我哪里出问题了?我是否正确传递了Bearer令牌,并且API结构不正确?预先谢谢你!
答案 0 :(得分:0)
首先,最好不要同时使用基于django方法和基于类的视图,并且在模型中仅使用auto_now = True
class Mymodel(models.Model):
emp= models.ForeignKey(User, on_delete = models.CASCADE)
time = models.DateTimeField(auto_now=True)
它会在创建实例时自动填充,而您无需这样做:
create_time = Mymodel.objects.create(emp=user, time=current_time)