From the docs:
Adding a foreign key from one of your own models to ContentType allows your model to effectively tie itself to another model class.
So we add a new model to our models called car which uses the Generic Relations.
class Car(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
created = models.DateTimeField()
class Meta:
ordering = ['-created']
def __str__(self):
return "{0} - {1}".format(self.content_object.series,
self.created.date())
We then update our models and define a post save handler.
def create_car(sender, instance, created, **kwargs):
"""
Post save handler to create/update car instances when
Bmw or Tesla is created/updated
"""
content_type = ContentType.objects.get_for_model(instance)
try:
car= Car.objects.get(content_type=content_type,
object_id=instance.id)
except Car.DoesNotExist:
car = Car(content_type=content_type, object_id=instance.id)
car.created = instance.created
car.series = instance.series
car.save()
And we add the post save handler to our Tesla model.
class Tesla(models.Model):
series = models.CharField(max_length=50)
created = models.DateTimeField()
class Meta:
ordering = ['-created']
def __str__(self):
return "{0} - {1}".format(self.series, self.created.date())
post_save.connect(create_car, sender=Tesla)
(and similarly added for Bmw model not show for brevity)
So now every time an instance of Tesla or Bmw is created or updated, the corresponding Car model instance gets updated.