I am trying to make a comments app for a Django project whereby each record can have a number of comments attached to it. However, when I try to migrate my model, I get the following error:
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "user_info"
What am I doing wrong?
Currently my models look like this:
users/models.py
class UserInfo(models.Model):
id = models.CharField(max_length=25, blank=False, null=False, primary_key=True)
dob = models.DateField(blank=True, null=True)
age = models.IntegerField(blank=True, null=True)
#Includes a number of other fields
def __str__(self):
return self.id
class Meta:
managed = False
db_table = 'user_info'
ordering = ['id']
comments/models.py
from users.models import UserInfo
class Comments(models.Model):
patient_record = models.ForeignKey(UserInfo, on_delete=models.CASCADE, null=True, blank=True)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
Just add unique=True
to your field and you should be good to go.
class UserInfo(models.Model):
id = models.CharField(max_length=25, blank=False, null=False, unique=True, primary_key=True)
dob = models.DateField(blank=True, null=True)
age = models.IntegerField(blank=True, null=True)
#Includes a number of other fields
def __str__(self):
return self.id
class Meta:
managed = False
db_table = 'user_info'
ordering = ['id']
The primary key needs to be unique to work. If not, you can simply have made two UserInfo
entries with the same id
, rendering the PK useless. On a separate note, why are you using your own id
field instead of the one already provided by Django?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.