开发者

django accessing subclasses of models

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


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'):
        ...


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.


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜