对contribute_to_class 的解释 [英] Explanation of contribute_to_class

查看:22
本文介绍了对contribute_to_class 的解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图扩展代码,但遇到了一个问题,我看不懂一行代码.我知道它的结果 - 但我不明白它是如何发生的,并且很自然地害怕改变它.

I'm attempted to extend code, and have come across an issue, I don't understand a line of code. I know the outcome of it - but I don't understand how it happens and am naturally enough scared to change it.

我遇到的代码行是这样的:

The line of code I've come across is this:

MyGenericRelation().contribute_to_class(model, 'field_name')

这段代码的结果是一个带有field_name"的字段被添加到模型"中,并且从我收集的字段内的对象是一个类型为 X 的列表(MyGenericRelation 的一部分).

The result of this code is a field with 'field_name' is added to the 'model' and from what I gather the objects inside the field are a list of type X (part of MyGenericRelation).

我想知道是否有人可以解释这是如何工作的.

I'm wondering if anyone can explain how this works.

正如,为什么我会得到一个附加到field_name"的 X 对象列表,如果它必须是contribute_to_class 之前的通用关系,或者使用实际的模型类型,说Y"只是给我一个列表是的.

As in, why do I get a list of X objects attached to 'field_name' and if does it have to be generic relations prior to contribute_to_class or would using an actual model type, say 'Y' just give me a list of Y's.

老实说,我对contribute_to_class 方法的影响和功能更感兴趣.

To be honest, I am more interested in the affect and functionality of the contribute_to_class method.

推荐答案

基本上,对于具有 contribute_to_class 方法的对象,当将它们添加到 Model 类时,我们调用 contribute_to_class 而不是 setattr:这允许对象在添加时对类进行额外的簿记和/或修改.Alex Gaynor 在这里有一个很好的解释:http://lazypython.blogspot.com/2008/11/django-models-digging-little-deeper.html

Basically, for objects that have a contribute_to_class method, when adding them to a Model class, we call contribute_to_class instead of setattr: this allows objects to do additional book-keeping and/or modification of the class as they are added. Alex Gaynor has a good explanation here: http://lazypython.blogspot.com/2008/11/django-models-digging-little-deeper.html

这篇关于对contribute_to_class 的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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