1👍
✅
You could have the relationship on the FinancialTransaction
using a Generic foreign key.
https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class FinatialTransation(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
Then the relationship exists in one place and there can only be 1.
Then from the FinancialTransaction
you check the object ID and the objects ContentType
and look it up accordingly.
ft = FinancialTransaction.objects.get(...)
thing = ft.content_type.get_object_for_this_type(id=ft.object_id)
Additionally you can then limit the GenericForeignKey to certain content types with:
class FinatialTransation(models.Model):
limit = models.Q(
models.Q(app_label='yourappsname', model='ThingOne') | models.Q(app_label='yourappsname', model='ThingTwo') | models.Q(app_label='yourappsname', model='ThingThree')
)
content_type = models.ForeignKey(ContentType, limit_choices_to=limit)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
Source:stackexchange.com