django访问模型的子类 [英] django accessing subclasses of models
本文介绍了django访问模型的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的django模型中使用子类,如下所示:
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):
...
在我看来,我想根据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:
...
但是这个给我一个DoesNotExist - 当Person是
驱动。有没有办法向Person类询问其子类?
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'):
...
这篇关于django访问模型的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文