The following code is specified:
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()
Now I want to request each BaseMedium.
b = BaseMedium.objects.all()
How to print each information, including subclass fields, without knowing what type of subclass?
b[0].a will print information if b[0] is actually associated with instance A , but if it is associated with B , it will print DoesNotExist Exception.
This makes sense, but I would like to have a shared variable or method that returns a related object.
Perhaps my database layout is not very good to request this path, if I were happy if you would recommend a better layout.
I was thinking about using 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 decision seems complicated, and I think you guys have better solutions.
python django django-models
rotrotrot
source share