问题
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.
Model class:
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)
When I run python3 manage.py migrate, it gives the following error:
django.core.exceptions.FieldError: Joined field references are not permitted in this query
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?
回答1:
Try fields=['userid_id'...
It looks like the UniqueConstraint
s are trying to join across to the user table.
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.
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.
If the behaviour is different with unique_together
, that might be considered a bug in UniqueConstraint
.
来源:https://stackoverflow.com/questions/59765118/django-model-uniqueconstraint-gives-an-error-when-migrating