I'm trying to solve a problem that I outlined in this question. At the moment it looks like I will have to override the to_python() method on the ForeignKey field. But as far as I can see in django's source code, the ForeignKey class doesn't actually have a to_python() method declared, so it must be inheriting it from the Field class, which would mean it looks like this:
def to_python(self, value):
"""
Converts the input value into the expected Python data type, raising
django.core.exceptions.ValidationError if the data can't be converted.
Returns the converted value. Subclasses should override this.
"""
return value
Only that can't be right... That means it's not throwing a ValidationError. And yet surely something must be throwing it... I mean the conversion of an id into the object must be happening somewhere and surely if the id was incorrect a ValidationError would be thrown?
Or perhaps the right question to ask is what other methods are called before the clean_<fieldname>
() method on a form? Which of these may 开发者_JS百科I want to override?
to_python
is used to convert an item from a database value to a Python one, in those cases where types differ. But a foreign key field is actually just an integer - the ID of the related object. So there is no conversion necessary, hence the empty method. The actual getting/displaying of the related object is done via a descriptor.
However, I don't know why you think you need to override to_python
on the ForeignKey. This has nothing whatever to do with the issue you mention in the linked question, ie having to create an object before linking to it. That is best done in the form's clean method, and I will add an answer there.
精彩评论