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)

identity_name='FacebookID'データベースの行の例は、とのFacebookIDservice_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()

Bobのインスタンスだとしましょうdjango.contrib.auth.models.User。で動的に生成されるBob.identities.facebook場所を使用して、FacebookIDにアクセスしたいと思います。facebookIdentitiesManager

これでコンテキストがわかりました。ここに質問があります。データベースからIDを取得して、それらをIdentitiesManager?で使用するにはどうすればよいですか。

読んでくれてありがとう。

4

2 に答える 2

0

私があなたの質問を理解した場合、あなたは次querysetのようにモデルを得ることができますManager

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

最後に、私はそれを行う方法を見つけました。dictに含まれるデータに基づいて、から継承するクラスを作成しdict、その属性(with )を作成しました。setattrクラスコードは次のとおりです。

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)

次に、ユーザークラスに追加するミックスインを作成しました。

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

もう1つのポイント:カスタムdictは再利用性を目的としていません:属性は更新されませんdict(うまくいけば、クラスのユースケースでは問題になりません)。

于 2012-11-19T15:58:27.163 に答える