how to know the database name from django.Model

Hi guys!! I am a newbie to django. I am leaning the model part and I have written a sample code in

from django.db import models

class Person(models.Model):
   full_name = models.CharField(max_length=100)
   def get_all_person
      return Person.objects.all():

next step I will try to configure multiple database using guide:

Just for curiosity, I don’t quite understand how does the Model know which database it will connect to ? which code maintain the db connection and let model run db queries over it ?
if I have two databases configured in the settings file
database[‘org1’] and database[‘org2’].
then I write a db routers following the guide.
is it possible to print which databases the model is running on in ?

You’ve got the right page to reference. Your questions are generally answered there.

The Model doesn’t connect to a database, a query does. You can specify which database to use for a query using the ‘using’ method. Each different query being run could involve a particular model using a different database - even if you’ve defined a router, because the using method would override it.

So the most accurate answer I can give is that any model could be used with every database connected to your application.

thanks for the reply!!
assuming I am using db router to choose DB not use “using” method, is there a attribute or parameter I can use in the model level to know which DB the query (like save()) will be running on ?

No - and it doesn’t make sense to try and find out.

The model isn’t connected to a database. A query connects to a database. It may make sense to figure out what database a specific query (or queryset) would use (or used), but that’s about it.

What is it you’re really trying to determine here? What functionality or purpose would you have for trying to identify this?

I want to create different cache for different databases. store them in a memcached. I will use the django cache system but in a decorator way:

from django.db import models

class Person(models.Model):
   full_name = models.CharField(max_length=100)

   @cache_with_key(user_name_key, timeout=3600*24*7)
   def get_all_person
      return Person.objects.all():

I will write some my code in cache_with_key on top of django.core.cache.
I am reading this doc:
this part is talking about route cache request to different cache tables in db.
it says:

If you don’t specify routing directions for the database cache model, the cache backend will use the default database.

so I want to create an cache array to store different database caches then use a method to get cache according to database name.


def get_cache_backend(database_name: Optional[str])  :
    if database_name is None:
        return default_cache
    return caches[database_name]

def create_cache_backend(database_name: Optional[str])  :
    if caches[database_name] is None:
        create_cache(database_name) #will call django.core.cache to create cache.
    return caches[database_name]

I plan to put the cache code in because I want to add my cache decorator code on the model functions.
but , as you said, I realize I cannot get the database name in model level !!

I’m really not understanding what you’re trying to say and do here. I’m also getting the (quite-possibly-wrong) impression that you’re not understanding what the Django Cache Framework does.

The Django cache framework is for Django to cache pages (and/or page fragments), not to cache database query results.

It’s quite possible that we’re dealing with an XY problem here, so lets dig a little deeper - what is it you’re trying to accomplish by doing this, and why do you think it may be necessary?

basically I want to is use cache to store some key-value pair from database:
from below doc django.core.cache has set,get function which I assume that can use for store data from database,
from django.core.cache import cache # this will return caches['default'].

cache.set('id1', 'Tim', 30)
cache.set('id2', 'Bob', 30)
person = cache.get(id_from_requst)

From this document, I think I can use cache to store key-value data ( I will write code to parse db data and save to cache). am I wrong ?

You can, the question is whether or not you should.

If your data is coming straight from your tables, you’re going to find that you’re going to expend a lot of effort trying to manage that cache rather than just querying your data from the database.

To get back to your original question, in whatever view that is being called that will issue your query to populate this cache - that’s where you can determine from which database your data is being retrieved.

However, if this is long-lived data, you may find it advantageous to keep this “parsed db data” as separate columns in your database, or possibly defined as model methods on the model to be accessible when needed.

So we’re just digging down now to the next level - why do you feel it’s necessary to cache this data to begin with? Do you have actual performance and response metrics that show there’s a problem to be resolved? Or is this just conjecture that you think you may get some improvement from doing this?