2012-04-29 53 views
7

我有一個使用多個數據庫的應用程序。一旦模型實例對象在內存中,我如何確定它來自哪個數據庫?具體而言,我想知道這在模型類的方法中使用。獲取數據庫django模型對象被查詢從

例子:

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}) 
+0

檢查http://stackoverflow.com/questions/9929629/how-to-get-the-database -d-model-instance-was-saved-in-in-django – okm

+0

[django模型是否知道它從哪個數據庫加載以及如何訪問此信息?](http:// stackoverflow。 COM /問題/ 4146781 /不-A-Django的模型,知道,從-該數據庫-IT-被加載和知識燦這-INFO) – Louis

回答

19

後豆蔻更多挖我發現:

self._state.db