如何给 Django 打补丁? [英] How to monkey patch Django?

查看:50
本文介绍了如何给 Django 打补丁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这篇关于猴子补丁 Django 的帖子:

I came upon this post on monkey patching Django:

from django.contrib.auth.models import User

User.add_to_class('openid', models.CharField(max_length=250,blank=True))

def get_user_name(self):
    if self.first_name or self.last_name:
        return self.first_name + " " + self.last_name
    return self.username

User.add_to_class("get_user_name",get_user_name)

我知道这并不理想,最好通过单独的模型 ProfileUser 添加字段和函数.

I understand that this isn't ideal and it's better to add fields and functions to User through a separate model Profile.

话虽如此,我只想了解这是如何工作的:

With that said, I just want to understand how this would work:

  1. 我会把猴子补丁代码放在哪里?

  1. Where would I put the monkey patching code?

代码什么时候运行——只运行一次?每个 Python 解释器启动一次?每个请求一次?

When is the code run -- just once? once per Python interpreter startup? once per request?

大概我仍然需要更改数据库架构.因此,如果我删除表 User 并运行 ./manage.py syncdbsyncdb 会知道"一个新字段已添加到用户?如果不是,我该如何更改架构?

Presumably I'd still need to change the DB schema. So if I dropped the table User and ran ./manage.py syncdb, would syncdb "know" that a new field has been added to User? If not how do I change the schema?

推荐答案

你可以把它放在任何地方,但是在设置文件(甚至 urlconf)中看到这种链接的东西是很常见的.任何可以放置信号的地方也可能是合适的.这段代码真的应该更智能一些 - 通常文件被导入不止一次,而且你无能为力,所以如果你尝试多次运行这样的代码,你可能会遇到问题.

You could put it anywhere, but it's common to see this kind of stuff linked in the settings file (or even the urlconf). Anywhere you could put a signal might also be appropriate. This code should really be slightly more intelligent - often files get imported more than once and there's not a lot you can do about it, so you can run into problems if you try to run code like this multiple times.

代码需要为每个python进程至少执行一次.

The code needs to be executed at least once for each python process.

是的,您需要手动更改数据库.Syncdb 可能不会发现更改(我没有仔细查看代码),但可能有一些地方可以放置可以工作的代码.

Yes you would need to change the DB by hand. Syncdb probably wouldn't catch the change (I haven't looked closely at the code), but there might be some places you could put the code that would work.

您似乎已经知道这是一件可怕的事情,永远不应该为真正的代码做这件事,所以我不会在这一点上赘述.除了在未来版本的 Django 中可能无法运行的代码之外,做这种事情是一种极好的方式,可以在代码中生成非常难以发现的错误.

You seem to already know that this is a terrible, horrible thing to do and should never be done for real code, so I won't belabor that point. Doing this kind of thing is a fantastic way to generate really difficult to find bugs in your code, in addition to code that may not work in future versions of Django.

此外,它不适用于您应该使用的 South.

Also, it won't work well with South, which you should be using.

这篇关于如何给 Django 打补丁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆