更正Django用户模型外键问题

时间:2019-04-25 23:10:35

标签: python django

我正在使用内置的django用户模型。我不断收到错误django.db.utils.IntegrityError: FOREIGN KEY constraint failed

我没有在其他任何模型中使用用户模型,反之亦然。

models.py看起来像这样

from django.contrib.auth.models import User
from django.utils import timezone
from django.db.models import CharField
from django.db.models import BooleanField
from django.db.models import TextField
from django.db.models import DateTimeField

class Course(models.Model): 
    id = models.AutoField(primary_key=True)
    name = CharField(max_length=100)

class Project(models.Model):
    id = models.AutoField(primary_key=True)
    desc = CharField(max_length=150)
    name = CharField(max_length=50)
    storyboard_file_path = TextField()
    storyboard_completed = BooleanField(default=False)
    filming_complete = BooleanField(default=False)
    audio_complete = BooleanField(default=False)
    production_complete = BooleanField(default=False)
    aggregation_complete = BooleanField(default=False)
    video_file_path = TextField()
    final_review_complete = BooleanField(default=False)
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="projects", null=True, blank=True)

class Status(models.Model):
    status_id = models.IntegerField(primary_key=True)
    desc = CharField(max_length=150)
    name = CharField(max_length=50)

class Event(models.Model):
    project_id = models.ForeignKey(Project, on_delete=models.CASCADE, null=True, blank=True)
    status_id = models.ForeignKey(Status, on_delete=models.CASCADE, null=True, blank=True)
    datetime = models.DateTimeField(auto_now_add=True, blank=True)

serializers.py看起来像这样

from rest_framework import serializers
from .models import Event
from .models import Project
from .models import Course
from rest_framework_jwt.settings import api_settings


class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 
        "password",
        "last_login",
        "is_superuser",
        "username",
        "first_name",
        "last_name",
        "email",
        "is_staff",
        "is_active",
        "date_joined",
        "groups",
        "user_permissions")

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance

    def get_jwt_token(user):
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        return jwt_encode_handler(payload)

class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ('id', 'desc', 'name', 'storyboard_file_path', 
        'storyboard_completed', 'filming_complete', 'audio_complete',  
        'production_complete', 'aggregation_complete', 'video_file_path',
        'final_review_complete', 'course')

    def create(self, validated_data):
        instance = self.Meta.model(**validated_data)
        instance.save()
        return instance

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
                setattr(instance, attr, value)
        instance.save()
        return instance

class CouserSerializer(serializers.ModelSerializer):
    projects = ProjectSerializer(many=True, read_only=True)

    class Meta:
        model = Course
        fields = ('id', 'name', 'projects')

    def create(self, validated_data):
        instance = self.Meta.model(**validated_data)
        instance.save()
        return instance

我正在尝试加载灯具

{
    "model": "auth.user",
    "pk": 1,
    "fields": {
        "password": "pbkdf2_sha256$120000$V2isoXl1Q88l$sVuB+25I6UNNLY76Ti0EixAu/Ucimqi7rFpbadDzqzc=",
        "last_login": null,
        "is_superuser": true,
        "username": "admin@admin.com",
        "first_name": "Admin",
        "last_name": "User",
        "email": "admin@admin.com",
        "is_staff": true,
        "is_active": true,
        "date_joined": "2019-04-16T00:16:13.252Z",
        "groups": [1],
        "user_permissions": []
    }
},
{
    "model": "auth.user",
    "pk": 2,
    "fields": {
        "password": "pbkdf2_sha256$120000$6YHv5JMayFnN$+Y2TqedyjZq02kEw/0ZaXtyigzaH2+BRUIqqkSeAG90=",
        "last_login": null,
        "is_superuser": false,
        "username": "content@content.com",
        "first_name": "Content",
        "last_name": "Manager",
        "email": "content@content.com",
        "is_staff": true,
        "is_active": true,
        "date_joined": "2019-04-16T00:19:01.130Z",
        "groups": [2],
        "user_permissions": []
    }
}
]

我不知道此外键错误来自何处。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

可能是团体。这些组是否存在(在用户之前)。如果没有,您将得到此错误。