django模型的方法
有没有更好的方法来处理模型内部的这些功能?
class MyModel ( models.Model ):
name = models.CharField( max_length=50 )
foo = models.CharField( max_length=50 )
def style_foo():
return '<a href="/contract/print/sample/%s/">%s</a>' % ( self.pk, _( 'View sample' ) )
style_foo.allow_tags = True
style_foo.short_description = _('Style sample')
我的模型本身已经超载了。这些函数使我的模型文件几乎不可读。我有几十个。我需要那些。
我正在做一个 CRM 系统,其中有大量的 contrib.admin 模板重载,因此有时更容易编写一两行方法,并在管理模型的 list_display = () 上使用它,而不是仅按顺序重写模板 admin/change_list_result.html更改一行。
我尝试在一个类中定义模型字段并使用这些方法在类中继承,但这很奇怪。
您有什么建议吗?
is there a better way to handle those functions inside the model?
class MyModel ( models.Model ):
name = models.CharField( max_length=50 )
foo = models.CharField( max_length=50 )
def style_foo():
return '<a href="/contract/print/sample/%s/">%s</a>' % ( self.pk, _( 'View sample' ) )
style_foo.allow_tags = True
style_foo.short_description = _('Style sample')
I have pretty much overloaded model itself. Those functions makes my model file barely unreadable. I have tens of them. I need those.
I am doing an CRM system with heavy contrib.admin templates overloading, therefore sometimes it easier to write a one or a two line method, and use it on Admin model's list_display = () and not rewrite template admin/change_list_result.html only in order to change one line.
I tried to define model fields in one class and inherit in class with those methods, but this is quite odd.
Do you have any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不完全确定你想做什么,但这可能会有所帮助。首先,作为一般规则,您不应将信息的格式/显示类型(例如 HTML)放入模型级别。您应该在其他地方格式化 HTML,并设计模型以便返回任何给定对象的 URL。例如:
I'm not entirely sure what you're trying to do, but this might be helpful. First, as a general rule, you shouldn't put formatting/display type of information (such as HTML) into the Model level. You should format the HTML elsewhere, and design the Model so as to return a URL for any given object. For instance:
get_absolute_url 适用于你想做什么?您只需将锚标记卸载到模板中并使用 get_absolute_url() 方法即可获取 url。如果您然后使用 永久链接装饰器 你可以将它直接绑定到你的 url 路由中。对合同/打印/样本视图的 url 进行的任何更改都将自动反映在整个站点中,而无需更新 models.py 文件以匹配新的 url 结构。
Would get_absolute_url work for what you're trying to do? You just offload the anchor tag into your template and use the get_absolute_url() method to get the url. If you then use the permalink decorator you can tie it right into your url routing. Any change to your urls for the contract/print/sample view will be automatically reflected throughout your site without having to update your models.py file to match the new url structure.