anon
anon

Reputation: 1069

Django : Multiple possible types in ForeignKey Field

I want to model the following relationship where the Vehicle owner field could be either a Person or a Company. How can we do that in Django?

class Person(models.Model):
    name = ...
    other_details = ...

class Company(models.Model):
    name = ...
    other_details = ...

class Vehicle(models.Model):
    owner = models.ForeignKey(x) # 'x' could be a Person or Company

Upvotes: 1

Views: 844

Answers (1)

Wagh
Wagh

Reputation: 4306

Use Generic foreign key ex.

class Vehicle(models.Model):
    content_type = models.ForeignKey(ContentType, null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True, blank=True)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

while saving the object you need to get the content_type of the model to which you want to give generic FK and object id of that model.

from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(Company)
object_id = company_object.id
ve = Vehicle()
ve.content_type = content_type
ve.object_id = object_id
ve.save()

hope this will help you.

Upvotes: 4

Related Questions