Reputation: 3
Been using Django for < 1yr now, but this one is new-to-me. Hopefully someone?
What I'm trying to do is read a Person object from one database (read/only, minimal person data) to populate my database (r/w, more extensive Person info).
I have 2 models, in different dbs:
everyone.py: class Person(models.Model): emplid = models.CharField(max_length=15,primary_key=True) ... (other fields deleted)
class Meta:
app_label = u'everyone'
db_tablespace = u'everyone'
db_table = u'people_names'
managed = False
people.py:
class Person(models.Model):
emplid = models.CharField(max_length=11, db_column='emplid', primary_key=True)
... (other fields deleted)
class Meta:
db_table = u'person'
app_label = u'commons'
db_tablespace = u'people'
The 2nd Person model is my default db, so #1 is "everyone.Person" and #2 is just "Person".
I tried (view.py):
try:
person = everyone.Person.objects.get(pk=emplid)
except everyone.Person.DoesNotExist: # person not found by "get"
do some stuff
finally:
do some other stuff
but django complains: global name 'everyone' is not defined.
If I substitute "Person" for "everyone.Person", this code works (but of course I access the wrong db.
When I do:
person = everyone.Person.objects.get(pk=emplid)
at the command line with a bad emplid, the shell correctly returns
condition everyone.Person.DoesNotExist raised
I can get around this problem using "filter" instead of "get", and deal with the returned QuerySet object, but I just wondered if anyone else noticed this and knows how to get "Get" to work in the case of accessing another db.
thx, Brian
Upvotes: 0
Views: 194
Reputation: 599610
This isn't how either Python namespaces or multiple databases work at all.
If you're defining both of those Person
classes in the same models.py file, then the second one completely overrides the first, and the first doesn't actually exist as far as Python is concerned.
Even if it did exist, you wouldn't refer to it as everyone.Person
. That would only be the case if you defined it inside a module called everyone.py, or if you defined it in a different app and did from everyone import models as everyone
.
Upvotes: 0