The following code is given:
class BaseMedium(models.Model):
title = models.CharField(max_length=40)
slug = models.SlugField()
class A(BaseMedium):
url = models.URLField()
class B(BaseMedium):
email = models.EmailField()
I now want to query every BaseMedium.
b = BaseMedium.objects.all()
How do I print every information including the subclass fields without knowing what the subclass type is?
b[0].a would print the information if b[0] is actually related to an A instance but if it's related to B it would print an DoesNotExist Exception. This makes sense but I'd like to have a common variable or method that returns the related object. Maybe my Database layout isn't really great to query that way if so I'd be glad if you'd recommend a better layout. I thought about using a GenericForeignKey
class Generic(models.Model):
basemedium = models.ForeignKey('BaseMedium')
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('content_type', 'object_id')
but this solution seems to be to complicated and I think you guys have better solutions.