0

I made an object WorkRelation that has an attribute contact that links to a Contact object. This is my models.py:

class WorkRelation(BaseModel):
    contact = models.OneToOneField(Contact, on_delete=models.CASCADE)
    limit = models.Q(app_label='groups', model="company") | models.Q(app_label='groups', model="bond")
    group_type = models.ForeignKey(ContentType, limit_choices_to=limit)
    group_id = models.PositiveIntegerField()
    group = GenericForeignKey('group_type', 'group_id')

    class Meta:
        app_label = 'groups'

    def __str__(self):
        return "Function %s" % self.group.__str__()

Somehow, I am not able to make multiple workrelation objects that link to the same contact, when I try this in the Django admin I get the following error:

Work relation with this Contact already exists.

This doesn't make sense to me because as far as I know, I don't say that the contact object should be unique. Does anybody know how I should adjust this model to make it possible to make multiple WorkRelation objects with the same contact?

hY8vVpf3tyR57Xib
  • 3,574
  • 8
  • 41
  • 86

1 Answers1

4

You are using models.OneToOneField which will allow a relation only between exactly one contact and one WorkRelation. If you want to reuse a certain contact for multiple WorkRelations, you will need to use models.ForeignKey:

class WorkRelation(BaseModel):
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE)

There's a great explanation here:

What's the difference between django OneToOneField and ForeignKey?

You can read more about the difference in the (excellent) Django documentation:

https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey https://docs.djangoproject.com/en/1.9/ref/models/fields/#onetoonefield

Community
  • 1
  • 1
Geotob
  • 2,847
  • 1
  • 16
  • 26