Custom Django Field is deciding to work as ForiegnKey for no reason

Posted by Joe Simpson on Stack Overflow See other posts from Stack Overflow or by Joe Simpson
Published on 2010-05-13T17:50:23Z Indexed on 2010/05/13 17:54 UTC
Read the original article Hit count: 243

Filed under:
|

Hi, i'm making a custom field in Django. There's a problem while trying to save it, it's supposed to save values like this 'user 5' and 'status 9' but instead in the database these fields show up as just the number.

Here is the code for the field:

def find_key(dic, val):
    return [k for k, v in dic.items() if v == val][0]

class ConnectionField(models.TextField):
    __metaclass__ = models.SubfieldBase
    serialize = False
    description = 'Provides a connection for an object like User, Page, Group etc.'
    def to_python(self, value):
        if type(value) != unicode:
            return value
        value = value.split(" ")
        if value[0] == "user":
            return User.objects.get(pk=value[1])
        else:
            from social.models import connections
            return get_object_or_404(connections[value[0]], pk=value[1])
    def get_prep_value(self, value):
        from social.models import connections
        print value, "prep"
        if type(value) == User:
            return "user %s" % str(value.pk)
        elif type(value) in connections.values():
            o=  "%s %s" % (find_key(connections, type(value)), str(value.pk))
            print o, "return"
            return o
        else:
            print "CONNECTION ERROR!"
            raise TypeError("Value is not connectable!")

Connection is just a dictionary with the "status" text linked up to the model for a StatusUpdate.

I'm saving a model like this which is causing the issue:

Relationship.objects.get_or_create(type="feedback",from_user=request.user,to_user=item)

Please can someone help, Many Thanks

Joe *_*

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models