Django用户模型外键

时间:2019-12-11 08:09:17

标签: python django django-rest-framework

我正在用Django编写关系数据库。 基本上,我想实现的目标是为其中一个表创建一个用户外键。

我在这里发现了很多类似的问题,但是由于某种原因,它似乎不适用于我的原因,也许是因为版本或我不知道。

这是我的模特

from django.contrib.auth.models import User


class Category(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

视图:

from rest_framework import viewsets
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated

from .models import Category
from .serializers import CategorySerializer


class CategoryView(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [IsAuthenticated]
    authentication_classes = [SessionAuthentication, BasicAuthentication]

为了强化,我使用了内置功能

path('api-auth/', include('rest_framework.urls')),

这是我得到的错误:

IntegrityError at /category/
NOT NULL constraint failed: category_category.user_id
Request Method: POST
Request URL:    http://127.0.0.1:8000/category/
Django Version: 2.2.5
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: category_category.user_id
Exception Location: C:\Users\Terkea\Anaconda3\envs\django_api_template\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383
Python Executable:  C:\Users\Terkea\Anaconda3\envs\django_api_template\python.exe
Python Version: 3.7.5
Python Path:    
['C:\\Users\\Terkea\\PycharmProjects\\django_api_template',
 'C:\\Users\\Terkea\\PycharmProjects\\django_api_template',
 'C:\\Program Files\\JetBrains\\PyCharm '
 '2019.2.3\\plugins\\python\\helpers\\pycharm_display',
 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\python37.zip',
 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\DLLs',
 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\lib',
 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template',
 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\lib\\site-packages',
 'C:\\Program Files\\JetBrains\\PyCharm '
 '2019.2.3\\plugins\\python\\helpers\\pycharm_matplotlib_backend']
Server time:    Wed, 11 Dec 2019 08:08:11 +0000

1 个答案:

答案 0 :(得分:1)

您可以覆盖perform_create方法。

class CategoryView(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [IsAuthenticated]
    authentication_classes = [SessionAuthentication, BasicAuthentication]


    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

来自文档:

  

perform_create(self,serializer)-保存新对象实例时,由CreateModelMixin调用。