Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

django - Explanation of 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')

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.

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...