Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get database django model object was queried from

I have an application which uses multiple databases. Once a model instance object is in memory, how can I determine what database it came from? Specifically I would like to know this for use in a method on the model class.

Example:

class book(Models.model):
    newdate = models.DateField(default=date.today())
    type = models.CharField(
                            max_length=30,
                            choices=BOOK_TYPE,
                            default = 'novel',
                            )
    def get_current_student(self):
        if not hasattr(self,'_current_student'):
            try:
                self._current_student = clickerlog.objects.using(SELF.ORIGIN_DATABASE).get(book=self.pk,end__isnull = True).student
            except:
                self._current_student = none
        return self._current_student

class booklog(Models.model):
    start = models.DateTimeField(
                                 default=datetime.now(),
                                 verbose_name = 'start time'
                                 )
    end = models.DateTimeField(null=True,blank=True,)
    book = models.ForeignKey(book)
    student = models.ForeignKey(student,
                              limit_choices_to = {'isactive':True})
like image 304
AgDude Avatar asked Apr 29 '12 18:04

AgDude


People also ask

How do I retrieve objects from the database in Django?

Django will complain if you try to assign or add an object of the wrong type. To retrieve objects from your database, construct a QuerySet via a Manager on your model class. A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters.

How do I write a SQL query in Django?

If you find yourself needing to write an SQL query that is too complex for Django’s database-mapper to handle, you can fall back on writing SQL by hand. Django has a couple of options for writing raw SQL queries; see Performing raw SQL queries. Finally, it’s important to note that the Django database layer is merely an interface to your database.

What is the database-abstraction API in Django?

Once you’ve created your data models, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete objects. This document explains how to use this API.

How to use get_object_or_404 () in a Django project?

How to use get_object_or_404 () in a Django Project? This function calls the given model and get object from that if that object or model doesn’t exist it raise 404 error. Suppose we want to fetch 3rd product from the product model then we can use:


1 Answers

After a litte more digging I found it:

self._state.db
like image 158
AgDude Avatar answered Oct 07 '22 20:10

AgDude