开发者

Help with creating a custom create and a custom get method

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 tha开发者_开发知识库t 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):

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)

As for getting a session when you have visit, and sequence_no there shouldn't be any custom code needed for that.


It would have to go in the manager, since that's where get and create reside. These are not methods of the model.

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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜