繁体   English   中英

Django中的元编程get_foo_display,foo_set等,它是如何工作的?

[英]Meta programming in Django get_foo_display, foo_set and others, how does it work?

我有一个配置文件UserProfile的用户模型。 不知何故,我的用户可以拥有多种类型的书籍:TA,TB,TC,TD。 这些选择在我的模型中的选择元组中定义(标准方式)。

从我的模板我希望能够打电话

{{ user.get_profile.has_book_type_TA }} 

并返回True / False。

TA是动态部分,可以重写为:

has_book_type_ [TYPE_NAME]

如何在模型中编写这种方法?

def has_book_type_(self, type_name):
    ...

但是如何使它可以调用为get_profile.has_book_type_TA

在模型的__init__方法中,遍历各种类型的书并创建属性:

for book_type in BOOK_TYPES:
  setattr(self, 'has_book_type_%s' % book_type, self.has_book_type_(book_type))

然后在您的模板中,检查user.get_profile.has_book_type_TA应该起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM