视频集模型具有Episode_number字段,在创建新的视频集时必须自动将其递增。每个故事都有情节,这些情节的episod_number字段以一个开头。怎么做?现在,我用户必须手动输入Episode_number。 story_id来自网址
class Story(models.Model):
title = models.CharField(max_length=255)
description = models.TextField(max_length=255)
cover = models.ImageField(upload_to=upload_location)
genre = models.ManyToManyField(Genre)
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Episode(models.Model):
title = models.CharField(max_length=255)
cover = models.ImageField(upload_to=upload_location)
story = models.ForeignKey(Story, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
episode_number = models.IntegerField(null=True)
class EpisodeView(viewsets.ModelViewSet):
serializer_class = EpisodeSerializer
permission_classes = [BasicAuthorizationPermissions]
def get_queryset(self):
story_id = self.kwargs['story_id']
return Episode.objects.filter(story=story_id)
def perform_create(self, serializer):
try:
story = Story.objects.get(pk=self.kwargs['story_id'])
except Story.DoesNotExist:
raise NotFound
if self.request.user != story.author:
raise PermissionDenied
return serializer.save(story=story)
答案 0 :(得分:1)
当基于参考Episod
模型Story
的{{1}}模型中有新条目时,应自动填充。
我们将覆盖episode_number
模型的默认保存方法,并检查这是否是新实例的条目,我们将从此处设置其值。
Episod