1

标题有点粗略,让我更详细地解释一下:

我有一个表Identity,它是一个像这样的简单表:

class Identity(models.model):

    identity_name = models.CharField(max_length=20, db_index=True) # name of the ID
    service_name = models.CharField(max_length=50)

数据库中的一个示例行是一个 Facebook 身份,其中identity_name='FacebookID'一个service_name='Facebook'.

现在,要将其链接到用户,我有下表:

class UserIdentity(models.Model):

    user = models.ForeignKey('django.contrib.auth.models.User', db_index=True)
    identity_type = models.ForeignKey('Identity', db_index=True)
    value = models.CharField(maxlength=50) # the ID value

    objects = models.Manager()
    identities = IdentitesManager()

假设Bobdjango.contrib.auth.models.User. 我想通过Bob.identities.facebook在.facebookIdentitiesManager

现在您知道上下文了,问题来了:我如何从数据库中检索身份,以便在IdentitiesManager?

谢谢阅读。

4

2 回答 2

0

Finally, I found how to do that. I created a class inheriting from dict and made it create its attributes (with setattr) based on the data contained in the dict. The class code is :

class IdentityDictionary(dict):
    """ 
        Create a custom dict with the identities of a user.
        Identities are accessible via attributes or as normal dict's key/value.

    """

    def __init__(self, user, key='service_name'):

        identities = UserIdentity.objects.filter(user=user)
        dict_identities = dict([ (getattr(user_id.identity, key).replace(' ', '').lower(), user_id.identity) for user_id in identities ])

        super(IdentityDictionary, self).__init__(dict_identities)

        for id_name, id_value in dict_identities.items():
            setattr(self, id_name, id_value)

Then I made a mixin to add to the user class:

class IdentitiesMixin(object):
""" 
    Mixin added to the user to retrieve identities 

"""
_identities_dict = {}
_is_identities_initialized = False

@property
def identities(self):
    if not self._is_identities_initialized :
        self._identities_dict = IdentityDictionary(self)
        self._is_identities_initialized = True

    return self._identities_dict

One more point: the custom dict is not intended for reusability : attributes are not updated if the dict is (hopefully, it is not a problem with the class use cases).

于 2012-11-19T15:58:27.163 回答
0

如果我理解了您的问题,您可以queryset在 as 中获取模型Manager

class IdentitiesManager(models.Manager):
    def  some_func(self):
        qs = super(IdentitiesManager, self).get_query_set()
于 2012-11-16T18:02:41.110 回答