I have the following two Django models:
class Project(models.Model):
identifier = models.CharField(max_length=128)
target_value = models.CharField(max_length=64)
...
Meta:
managed='False'
db_table='projects'
class MainProjects(models.Model):
mp_identifier = models.CharField(max_length=128)
some_value = models.CharField(max_length=256)
...
The database housing the Project model is actually off in a cloud database somewhere and is actually used by a completely different application written by a separate team. I need to be able to ask Django to pull a list of MainProjects and somehow annotate the target_value from the Project model into the QuerySet.
I've tried using .extra() but the documentation is slim and the examples I've been able to find so far haven't worked for me. I'd also like to avoid using raw SQL if at all possible.
Right now, I'm getting around the problem by using a management command I wrote for the Django application to go and fetch the target_value from the remote database and store it as MainProjects model attribute so that I can just reference it locally but - yuck.
Thoughts? Suggestions?
CodePudding user response:
I would recommend having a thorough read of this section of the documentation.
https://docs.djangoproject.com/en/4.0/ref/models/options/#django.db.models.Options.managed
It explains the managed option with a good amount of detail.
Also, when it comes to connecting to a different database, you can set up as many database connections as you like, specifying them in your settings.py file.
The way most if not all sql servers work is by TCP or sockets. I would recommend sockets where possible, however, because you need to connect to a remote server, its more than likely easier to connect via TCP.
Knowing that you can punch in, any IP address, port, username, password, etc. And be able to connect to a server at that address which is hosting a sql server, well, thats a matter of knowing the relevant connection information and then telling django about it. As an example:
DATABASES = {
'remote_unmanaged': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '[the database name]',
'USER': '[the database user with remote access privilege]',
'PASSWORD': '[password for user above]',
'HOST': '[server ip address]',
'PORT': '',
}
}
And furthermore to use a queryset from your remote connection server you can take a look here:
One more thing I just noticed about on of the meta objects on your model:
class Project(models.Model):
identifier = models.CharField(max_length=128)
target_value = models.CharField(max_length=64)
class Meta:
managed=False # <-- here, literal False, not str which was truth, which means it was actually considered a managed model :)
db_table='projects'
