简体   繁体   English

在 django 中创建新 object 时出现“唯一约束失败:main_chatroom.admin_id”

[英]'UNIQUE constraint failed: main_chatroom.admin_id' when creating new object in django

it only happens when I create new chatroom with the same admin this is what I wrote in my models.py只有当我用同一个管理员创建新聊天室时才会发生这种情况,这是我在 models.py 中写的

class ChatRoom(models.Model):
    id = models.UUIDField(primary_key=True, unique=True,
                          default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100, null=False, blank=True)

    users = models.ManyToManyField(User, through='Membership')
    admin = models.ForeignKey(
        User, null=False, blank=False, on_delete=models.CASCADE, related_name='admin')
    date_created = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class Membership(models.Model):
    id = models.UUIDField(primary_key=True, unique=True,
                          default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    chatroom = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)
    date_joined = models.DateTimeField(auto_now=True, null=False, blank=False)

    def __str__(self):
        return self.user

    class Meta:
        unique_together = [['user', 'chatroom']]

when i write this in the shell:当我在 shell 中写这个时:

from .main.models import ChatRoom,Membership
from django.contrib.auth.models import User         
user  = User.objects.get(username = 'someone')
chatroom = ChatRoom(admin = user, name = 'something')
chatroom.save()
chatroom2 = ChatRoom(admin = user, name = 'somethingElse')
chatroom2.save()

after i save chatroom2 i get this error: django.db.utils.IntegrityError: UNIQUE constraint failed: main_chatroom.admin_id can anyone help me?保存 chatroom2 后,我收到此错误: django.db.utils.IntegrityError: UNIQUE constraint failed: main_chatroom.admin_id谁能帮我?

so it turned out that i did something that made all migrations does not have any affect on the database so i created new project and copied all my code to the new project( yes i know this is not the right way to do things but it was the easiest way for me) and everything now works great所以事实证明我做了一些使所有迁移对数据库没有任何影响的事情所以我创建了新项目并将我的所有代码复制到新项目中(是的,我知道这不是正确的做事方式,但它是对我来说最简单的方法),现在一切都很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM