django accessing subclasses of models

2020-07-16 02:33发布

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

3条回答
做自己的国王
2楼-- · 2020-07-16 03:07

The django-polymorphic module does actually greatly the job and is fairly simple to use.

查看更多
地球回转人心会变
3楼-- · 2020-07-16 03:10

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.

查看更多
Juvenile、少年°
4楼-- · 2020-07-16 03:12

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'):
        ...
查看更多
登录 后发表回答