简体   繁体   中英

IntegrityError “Exception: Field is not unique” for a OneToOneField with unique=True in django models

I have the following in models.py

class Groups(models.Model):
  name = models.CharField(max_length=20)
  calls_lim = models.IntegerField(blank=True,null=True,max_length=2,unique=False)
  time_lim = models.IntegerField(max_length=4,blank=True,null=True,unique=False)
  ivr = models.OneToOneField(ivr,unique=False)

  def __unicode__(self):
    return u'%s' % (self.name)

class UserProfile(models.Model):
  user = models.OneToOneField(User)
  phone = models.IntegerField(max_length=12)
  group = models.OneToOneField(Groups,unique=False)
  msg_rcv = models.IntegerField(default=0,blank=True,null=True)
  msg_snt = models.IntegerField(default=0,blank=True,null=True)
  last_call = models.DateTimeField(blank=True,null=True)
  pin = models.IntegerField(max_length=6,blank=True,null=True)
  blacklist = models.BooleanField(default=False)

  def __unicode__(self):
    return u'%s' % (self.user)

When i try to do an insert for UserProfile, the field group throws this exception

Exception Value: column group_id is not unique

Snippet from views.py that causes Exception

group = Groups.objects.get(name=str(form.cleaned_data['group']))
UserProfile.objects.create(user=User,phone='12345',group=group)

Is this expected behavior? Is it wrong to use OneToOneField for group?

Thanks

Intuitively I would think Groups and Users have a many to many relationship (A user can be part of many groups and a group can consist of many users). If that is the case, use a ManyToManyField instead.

If in your case a User can be part of only one group, the group-user relationship is one to many and thus the UserProfile model needs to have a ForeignKey to group.

A OneToOnefield is used ONLY for a one to one relationship between two models.

Refer https://docs.djangoproject.com/en/dev/ref/models/fields/#module-django.db.models.fields.related

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.

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