[Django]-OneToMany Relationship for more generic django apps

0πŸ‘

βœ…

It looks like generic relation. See: here to django documentation. Generic foreign keys and relations sometimes cause issues in later development process but you can also consider this:

class Payment(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    amount = models.IntegerField()

And in leaseapp

class Lease(models.Model):
    leaserholder = models.CharField(max_length=300)

class LeasePayment(models.Model):
    lease = models.ForeignKey(Lease)
    payment = models.OneToOneField(Payment)

Advantage: there is no magic behind and your database model is clear.

0πŸ‘

You can achieve this using a GenericForeignKey. To do this you need the content_type, object_id and content_object properties on the Payment model.

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType


class Payment(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    created_at = models.DateTimeField(auto_now_add=True)
    amount = models.IntegerField()

Then you can create a lease payment like this. This will work for any model. So if you create a Fee model you can also create payments for that

class Lease(models.Model):
    leaserholder = models.CharField(max_length=300)

lease = Lease.object.first()
Payment.objects.create(content_object=lease, amount=700)

Note: this requires that django.contrib.contenttypes be installed, which is by default in most django apps. For more info check out the docs page on contenttypes

πŸ‘€Brobin

Leave a comment