IntegrityError "Excepción: el campo no es único" para OneToOneField con unique = True en los modelos de django

I have the following in

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' % (

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 that causes Exception

group = Groups.objects.get(name=str(form.cleaned_data['group']))

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

Muchas Gracias

preguntado el 27 de agosto de 11 a las 21:08

"create(user=User,...)"? You're either hiding the User model by writing User = ... or trying to convert the User model class to a User id, which makes no sense. -

Also, you shouldn't be setting null=True en todo. msg_snt y msg_rcv make no sense as None en lugar de 0, for example. Also, max_length does nothing on IntegerField. Finally, what's an ivr? -

1 Respuestas

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.


Respondido 30 ago 11, 17:08

Thanks... i was confused with sql relations. - ggss

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.