[英]Meta programming in Django get_foo_display, foo_set and others, how does it work?
I have a user model with a profile UserProfile. 我有一个配置文件UserProfile的用户模型。 Somehow my user can have several type of books: TA, TB, TC, TD.
不知何故,我的用户可以拥有多种类型的书籍:TA,TB,TC,TD。 Those choices are defined in a choices tuple in my model (standard way).
这些选择在我的模型中的选择元组中定义(标准方式)。
From my template I would like to be able to call 从我的模板我希望能够打电话
{{ user.get_profile.has_book_type_TA }}
and returns True/False. 并返回True / False。
TA is the dynamic part, it could be rewritten as: TA是动态部分,可以重写为:
has_book_type_[type_name] has_book_type_ [TYPE_NAME]
How can I write this kind of method in my model ? 如何在模型中编写这种方法?
def has_book_type_(self, type_name):
...
But how to make it callable as get_profile.has_book_type_TA 但是如何使它可以调用为get_profile.has_book_type_TA
In the __init__
method for your model, walk through the different types of books and create properties: 在模型的
__init__
方法中,遍历各种类型的书并创建属性:
for book_type in BOOK_TYPES:
setattr(self, 'has_book_type_%s' % book_type, self.has_book_type_(book_type))
Then in your templates, checking user.get_profile.has_book_type_TA
should work. 然后在您的模板中,检查
user.get_profile.has_book_type_TA
应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.