2011-06-30 77 views
0

我有兩個型號,像這樣:幫助創建一個自定義創建和自定義get方法

class Visit(models.Model): 
    id = models.AutoField(primary_key=True) 
    name = models.CharField(max_length=65535, null=False) 

class Session: 
    id = models.AutoField(primary_key=True) 
    visit = models.ForeignKey(Visit) 
    sequence_no = models.IntegerField(null = False) 

我要兩個編寫自定義的Session模型建立方法,所以當我寫這篇文章:

visitor = Vistor.objects.get(id=1) 
new_session = Session.objects.create_new_session(visit=visitor) 

...我得到的Session表中的新紀錄,爲遊客即3。這裏的下一個連續的序列號是一些示例數據

VISITOR SEQUENCE_NO 
------- ----------- 
1   1 
1   2 
2   1 
2   2 
1   3 (This would be the row that would be created) 

另一個是寫一個自定義得到的Session模型的方法,讓我寫:

visitor = Vistor.objects.get(id=1) 
new_session = Session.objects.get_session(visit=visitor, sequence_no=3) 

...我得到最高的序列號是訪問者的紀錄。下面是一些示例數據

VISITOR SEQUENCE_NO 
------- ----------- 
1   1 
1   2 (This would be the row that would be fetched) 
2   1 
2   2 
1   3 

你能告訴我如何做到這一點嗎?這個代碼是否應該放在Model或Manager中?

謝謝大家。

回答

2

這將出現在會話管理器中。它看起來是這樣的(未經測試):

class SessionManager(models.Manager): 
    def new_session(self, visit, **kwargs): 
     vs = self.model.objects.filter(visit=visit).order_by("-sequence_no")[:1] 
     if len(vs): 
      kwargs.update({"sequence_no": vs.sequence_no + 1}) 
     return Super(SessionManager, self).create(visit=visit, **kwargs) 

至於得到一個會話,當你有訪問,並sequence_no不應該有需要的任何自定義代碼。

+0

比賽條件... –

+0

嗨唐納德,我不能效仿這一點:'如果len(vs):'。那個有什麼用途?謝謝。 –

+0

它檢查QuerySet的長度。如果沒有這個人的條目,那麼它將是0,如果有一個條目,它將是1。 –

1

這將不得不在經理,因爲這是getcreate駐留。這些不是模型的方法。

class SessionManager(models.Manager): 
    def get(self, *args, **kwargs): 
     # your stuff here 
     return super(SessionManager, self).get(*args, **kwargs) 

    def create(self, *args, **kwargs): 
     # your stuff here 
     return super(SessionManager, self).create(*args, **kwargs) 

class Session(models.Model): 
    ... 
    objects = SessionManager()