开发者

"Foreign Keys" across very separate databases in Django

开发者 https://www.devze.com 2023-02-03 08:05 出处:网络
I\'ve writing a Django site that uses two different databases. One is the local, let\'s call it, \"Django\", database that stores all of the standard tables from a pretty standard install -- auth, sit

I've writing a Django site that uses two different databases. One is the local, let's call it, "Django", database that stores all of the standard tables from a pretty standard install -- auth, sites, comments, etc. -- plus a few extra tables.

Most of the data, including users, comes from a database on another server, let's call it the "Legacy" database.

I'm looking for suggestions on clean, pythonic ways of connecting the two databases, particularly in regards to users.

I'm using a proxy model, which works great when I can explicitly use it, but I run into problems when I'm accessing the user object as a related object (for example, when using the built-in django comments system).

Here's what the code looks like:

models.py: (points to the Django database)

from django.db import models
from django.conf import settings
from django.contrib.auth.models import User as AuthUser, UserManager as AuthUserManager, AnonymousUser as AuthAnonymousUser

class UserPerson(models.Model):
    user = models.OneToOneField(AuthUser, related_name="person")
    person_id = models.PositiveIntegerField(verbose_name='Legacy ID')

    def __unicode__(self):
        return "%s" % self.get_person()

    def get_person(self):
        if not hasattr(self, '_person'):
            from legacy_models import Person
            from utils import get_person_model
            Person = get_person_model() or Person
            self._person = Person.objects.get(pk=self.person_id)
        return self._person
    person=property(get_person)

class UserManager(AuthUserManager):
    def get_for_id(self, id):
        return self.get(person__person_id=id)

    def get_for_email(self, email):
        try:
            person = Person.objects.get(email=email)
            return self.get_for_id(person.pk)
        except Person.DoesNotExist:
            return User.DoesNotExist

    def create_user(self, username, email, password=None, *args, **kwargs):
        user = super(UserManager,self).create_user(username, email, password, *args, **kwargs)
        try:
            person_id = Person.objects.get(email=email).pk
            userperson, created = UserPerson.objects.get_or_create(user=user, person_id=person_id)
        except Person.DoesNotExist:
            pass
        return user

class AnonymousUser(AuthAnonymousUser):
    class Meta:
        proxy = True

class User(AuthUser):
    class Meta:
        proxy=True

    def get_profile(self):  
        """
        Returns the Person record from the legacy database
        """
        if not hasattr(self, '_profile_cache'):
            self._profile_cache = UserPerson.objects.get(user=self).person
        return self._profile_cache

    objects = UserManager()

legacy_models.py: (points to the "Legacy" database)

class Person(models.Model):
    id = models.AutoField(primary_key=True, db_column='PeopleID') # Field name made lowercase.
    code = models.CharField(max_length=40, blank=True, db_column="person_code", unique=True)
    first_name = models.CharField(max_length=50, db_column='firstName', blank=True) # Field name made lowercase.
    last_name = models.CharField(max_length=50, db_column='lastName', blank=True) # Field name made lowercase.
    email = models.CharField(max_length=255, blank=True)

    def __unicode__(self):
        return "%s %s" % (self.first_name, self.last_name)

    def get_user(self):
        from models import User
        if not hasattr(self,'_user'):
            self._user = User.objects.get_for_id(self.pk)
        return self._user
    user = property(get_user)

    class Meta:
        db_table = u'People'

I've also whipped up my own middleware, so request.user is the proxy User object also.

The real problem is when I'm using something that has user as a related object, 开发者_运维知识库particularly in a template where I have even less control.

In the template:

{{ request.user.get_profile }} 
{# this works and returns the related Person object for the user #}

{% for comment in comments %} {# retrieved using the built-in comments app %}
    {{ comment.user.get_profile }}
    {# this throws an error because AUTH_PROFILE_MODULE is not defined by design #}
{% endfor %}

Short of creating a wrapped version of the comments system which uses my proxy User model instead, is there anything else I can do?


Here's how I resolved it. I stopped using the User proxy altogether.

models.py:

from django.db import models
from legacy_models import Person
from django.contrib.auth.models import User

class UserPerson(models.Model):
    user = models.OneToOneField(User, related_name="person")
    person_id = models.PositiveIntegerField(verbose_name='PeopleID', help_text='ID in the Legacy Login system.')

    def __unicode__(self):
        return "%s" % self.get_person()

    def get_person(self):
        if not hasattr(self, '_person'):
            self._person = Person.objects.get(pk=self.person_id)
        return self._person
    person=property(get_person)

class LegacyPersonQuerySet(models.query.QuerySet):
    def get(self, *args, **kwargs):
        person_id = UserPerson.objects.get(*args, **kwargs).person_id
        return LegacyPerson.objects.get(pk=person_id)

class LegacyPersonManager(models.Manager):
    def get_query_set(self, *args, **kwargs):
        return LegacyPersonQuerySet(*args, **kwargs)

class LegacyPerson(Person):
    objects = LegacyPersonManager()

    class Meta:
        proxy=True

and legacy_models.py:

class Person(models.Model):
    id = models.AutoField(primary_key=True, db_column='PeopleID') # Field name made lowercase.
    code = models.CharField(max_length=40, blank=True, db_column="person_code", unique=True)
    first_name = models.CharField(max_length=50, db_column='firstName', blank=True) # Field name made lowercase.
    last_name = models.CharField(max_length=50, db_column='lastName', blank=True) # Field name made lowercase.
    email = models.CharField(max_length=255, blank=True)

    def __unicode__(self):
        return "%s %s" % (self.first_name, self.last_name)

    def get_user(self):
        from models import User
        if not hasattr(self,'_user'):
            self._user = User.objects.get_for_id(self.pk)
        return self._user
    def set_user(self, user=None):
        self._user=user
    user = property(get_user, set_user)

    class Meta:
        db_table = u'People'

Finally, in settings.py:

AUTH_PROFILE_MODULE = 'myauth.LegacyPerson'

This is a simpler solution, but at least it works! It does mean that whenever I want the legacy record I have to call user_profile, and it means that there's an additional query for each user record, but this is a fair trade-off because actually it isn't very likely that I will be doing a cross check that often.

0

精彩评论

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