Reputation: 3915
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?
Upvotes: 0
Views: 409
Reputation: 2945
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
Upvotes: 4