我有两个型号,像这样:帮助创建一个自定义创建和自定义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中?
谢谢大家。
比赛条件... –
嗨唐纳德,我不能效仿这一点:'如果len(vs):'。那个有什么用途?谢谢。 –
它检查QuerySet的长度。如果没有这个人的条目,那么它将是0,如果有一个条目,它将是1。 –