开发者

Storing additional info about users in Django

For some reasons (particularly, to try making DB scheme upgrading easier), I need to store all the user's extended properties in another object (like in this question to separate Person and Address)

I have an AUTH_PROFILE_MODULE override set and do capture def_user_profile.

class CustomUser(models.Model):
    user = models.ForeignKey(User, unique=True)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        CustomUser.objects.create(user=instance)

The question is: if I add a custom type property to CustomUser, like this:

class CustomPropertySet(models.Model):
    this_is_a_Farmer 开发者_高级运维= models.BooleanField()

class CustomUser(models.Model):
    user = models.ForeignKey(User, unique=True)
    extdata = models.CustomProperySet()

Will this automatically create a CustomProperySet entry at adding new user? Does CustomPropertySet needs to be associated back with ForeignKey to its CustomUser owner? Second question: how to delete extended properties like this when object is deleted?


The obvious answer to these is "try it and find out", but we're a polite people here...

  • Will it automatically create CustomPropertySet?

When you assign something to extdata what do you assign? Assigning True and False probably won't work, you'd have to assign a CustomPropertySet instance, and to get one you'll have to create one.

Try it and this will become clear.

  • Does CustomPropertySet need to point back to a CustomUser instance?

No. The CustomProper t ySet can survive all on it's lonesome. Your CustomUser points to it, but it's not bashful and doesn't care who or how many people point at it.

  • How do delete cascading dependancies?

See the documentation about cascading deletes


You can't assign a model as a field of another model. It just doesn't work that way. Apart from anything else, there's a whole load of metaclass magic going on to turn model-level field declarations into instance-level attributes, and that simply won't work with a model like you have tried with CustomProperySet.

I can't really understand what you are trying to do, anyway. If you want extra data in your profile class, just add it - if you want the structure of that data shared with other classes, maybe subclassing would help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜