问题
I'm using subclasses in my django-models like this:
class Person(models.Model):
name = models.CharField(max_length=100)
...
class Butcher(Person):
...
class Driver(Person):
...
In my view i want to do certain things depending on the subclass of the Person-class, like this:
def person_detail_view(request, slug):
person = Person.objects.get(slug=slug)
if person.butcher:
...
elif person.driver:
...
But this gives me a DoesNotExist-Error when the Person is a Driver. Is there a way to ask the Person class for its subclass?
Thanks in advance Jacques
回答1:
Your basic logic is sound; the problem is in how you're testing. You have to check for the presence of the attribute, not it's value. For example:
def person_detail_view(request, slug):
person = Person.objects.get(slug=slug)
if hasattr(person, 'butcher'):
...
elif hasattr(person, 'driver'):
...
回答2:
You can't do that. Person
model queries a different table - appname_person
, Butcher
, a different one and Driver
another.
The inheritance in Django models only saves you the writing of the fields again and doesn't query multiple tables - It shouldn't either.
To achieve something to this effect you should have a Person.type
in the db, or you should use Generic Relations, where you make Person
to have generic relations with all of the subtypes you intend to create (without actually inheriting, and defining generic foreignkey.)
If the fields in each of those models are same, just add a type
field to the person; or if the fields are quite different, follow the generic relations approach.
回答3:
The django-polymorphic module does actually greatly the job and is fairly simple to use.
https://github.com/chrisglass/django_polymorphic
https://django-polymorphic.readthedocs.org/en/latest/
来源:https://stackoverflow.com/questions/5855358/django-accessing-subclasses-of-models