I have two models like so:
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)
I’d like two write a custom create method in the Session model so when I write this:
visitor = Vistor.objects.get(id=1)
new_session = Session.objects.create_new_session(visit=visitor)
…I get a new record in the Session table with the next consecutive sequence number for that visitor i.e. 3. Here’s some sample data
VISITOR SEQUENCE_NO
------- -----------
1 1
1 2
2 1
2 2
1 3 (This would be the row that would be created)
The other was writing a custom get method in the Session model so that I write:
visitor = Vistor.objects.get(id=1)
new_session = Session.objects.get_session(visit=visitor, sequence_no=3)
…I get the previous record of that visitor with the highest sequence number. Here’s some sample data
VISITOR SEQUENCE_NO
------- -----------
1 1
1 2 (This would be the row that would be fetched)
2 1
2 2
1 3
Could you tell me how to accomplish this please? Should this code be in the Model or the Manager?
Thanks everyone.
This would be in a Manager for Sessions. It would look something like (untested):
As for getting a session when you have visit, and sequence_no there shouldn’t be any custom code needed for that.