我有两个这样的模型:
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)
另一个是在模型中编写自定义 get 方法,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
你能告诉我如何做到这一点吗?此代码应该在模型中还是管理器中?
谢谢大家。