Django:模型UniqueConstraint迁移时出现错误 [英] Django: Model UniqueConstraint gives an error when migrating

查看:44
本文介绍了Django:模型UniqueConstraint迁移时出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django项目中,在其中一个模型中,我需要使用两个UniqueConstraint实例.但是,当我添加它并在运行makemigrations之后进行迁移时,会在终端中显示错误.

In my Django project the in one of the model I need to use two UniqueConstraint instances. But when I add that and do the migration after running makemigrations it gives an error in the terminal.

模型类:

class MyDays(models.Model):
    class Meta:
        verbose_name = "My Day"
        verbose_name_plural = "My Days"
        constraints = [
            models.UniqueConstraint(fields=['userid', 'date', 'from'], condition=Q(status=1), name='user_date_from_a'),
            models.UniqueConstraint(fields=['userid', 'date', 'to'], condition=Q(status=1), name='user_date_to_b')
        ]

    id = models.BigAutoField(primary_key=True)
    userid = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="User")
    date = models.DateField(auto_now_add=False, editable=True, validators=[validate_date])
    from = models.TimeField(auto_now_add=False, editable=True)
    to = models.TimeField(auto_now_add=False, editable=True)
    status = models.ForeignKey(Status, on_delete=models.CASCADE, verbose_name="Status", default=1)

当我运行python3 manage.py migration时,它出现以下错误:

When I run python3 manage.py migrate, it gives the following error:

django.core.exceptions.FieldError:联接的字段引用不是此查询允许

django.core.exceptions.FieldError: Joined field references are not permitted in this query

仅当状态为1以及其他3个字段组合时,我才需要具有唯一记录.我究竟做错了什么?如何解决此错误?

I need to have unique records only if the status is 1 along with the other 3 field combination. What am I doing wrong? How can I fix this error?

推荐答案

尝试 fields = ['userid_id'...

似乎 UniqueConstraint 正在尝试连接到用户表.

It looks like the UniqueConstraints are trying to join across to the user table.

Django使用您的ForeignKeys和OneToOneFields并在末尾添加 _id 以创建存储相关对象的主键(通常是整数)的DB列.因此,通常不应在相关对象名称的末尾添加"id".

Django takes your ForeignKeys and OneToOneFields and adds _id to the end to create the DB column storing the related object's primary key (usually an integer). You generally shouldn't put "id" on the end of related object names for that reason.

因此,如果 my_days MyDays 的实例,则 my_days.userid 是用户实例,而 my_days.userid_id (通常)是整数.

So if my_days is an instance of MyDays, then my_days.userid is a user instance and my_days.userid_id is (usually) an integer.

如果行为与 unique_together 不同,则可以认为这是 UniqueConstraint 中的错误.

If the behaviour is different with unique_together, that might be considered a bug in UniqueConstraint.

这篇关于Django:模型UniqueConstraint迁移时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆