Models.py
class Season(models.Model):
name = models.CharField()
statuses = models.CharField()
class Match(models.Model):
SHOT_CHOICES = (
('W', 'Win'),
('F', 'Fail'),
('D', 'Draw'),
)
season = models.ForeignKey(Season, on_delete=models.CASCADE)
status = models.CharField(choices=STAT_CHOICE, max_length=1)
我用于创建匹配项的视图
class CreateMatches(generics.CreateApiView)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data, many=True)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
statuses是一个类似“ WFFWFDDW”的字符串,我需要从外键季节的状态中获取“ nth”个字符,将状态转换为“ nth”个匹配。
答案 0 :(得分:0)
由于 status
模型的Match
字段不依赖于请求中的任何输入数据,因此您可以通过覆盖 {{1} } 方法的 save()
模型。但是,您必须设置 Match
null=True
答案 1 :(得分:0)
我通过重写perform_create函数来解决了该问题
def perform_create(self, serializer):
if type(serializer.validated_data) == list:
for iter,item in enumerate(serializer.validated_data):
season = item['season']
count = season.matches.count()
status = season.statuses[count+iter]
item.update({'status':status})
serializer.save()