Question

I have an auto-increment field called sequence. I only want it to increment by 1 within the topic this model is in. Usually the most would ever be is about 10. Then resets for a new topic. I would like this to be done in a save override method:

class Video(TimeStampedModel):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200)
    description = models.CharField(max_length=500)
    topic = models.ForeignKey('video.VideoTopic')
    sequence = models.IntegerField(default=1)

    def save(self, *args, **kwargs):
        # Get last value of sequence and increment by 1
        top = Video.objects.order_by('-sequence')[0]
        self.sequence = top.sequence + 1
        super(Video, self).save()

Problem with my code here is that "top" in the save method will only get the video with the highest numbered sequence.

How do I get the topic of the video being saved from which to filter my query properly?

Was it helpful?

Solution

Get it from self.topic:

top = Video.objects.filter(topic=self.topic).order_by('-sequence')[0]

You can also use latest() instead of sorting and taking [0] out of the queryset:

top = Video.objects.filter(topic=self.topic).latest('sequence')

In this case latest() would get the single Video model instance that has the maximum sequence value for the particular topic.

See also: Overriding predefined model methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top