只有当数据库中必须有 1 到 99 个数字时,如何才能存储数字 100

how can store the number 100 only when 1 to 99 numbers are must have inside the db

假设我正在添加 matchround_5,第 1、2、3、4 轮必须在数据库中,检查数据库中是否存在每一轮,我该如何解决这个问题?

Modelserializer

class MatchScoreSerializer(serializers.ModelSerializer):

def create(self, validated_data):
    gameevent = validated_data.get('gameevent')
    match_round =validated_data.get('match_round')
    match = Matchscore.objects.filter(gameevent=gameevent,match_round=match_round).first()
    if match :
        validated_data = Matchscore.objects.filter(gameevent=gameevent,match_round=match_round).update(**validated_data)
        match.refresh_from_db()
        return validated_data
    else:
        return Matchscore.objects.create(**validated_data)
       
    
def validate(self, validated_data):
    gameevent = validated_data.get('gameevent')
    match_round =validated_data.get('match_round')
    if not match_round :
        raise serializers.ValidationError("Enter value more than 0")
    if match_round == 1:
        return validated_data
    round = range(1,match_round)
    match = Matchscore.objects.filter(gameevent=gameevent,match_round__in=round).values_list('match_round',flat=True)
    match = set(match)
    if match :
        return validated_data
    if len(match)== match_round-1:
        return validated_data
    else:
        raise serializers.ValidationError("Enter a valid match_round")

Here my model

class Matchscore(TimeStampedModel):
gameevent = models.ForeignKey(GameEvent, null=True, related_name='game_event',on_delete=models.DO_NOTHING)
match_round = models.IntegerField(null=True,blank=True)
team_a = models.ForeignKey(Team,null=True,related_name='team_one',on_delete=models.DO_NOTHING)
team_a_score = models.PositiveIntegerField(null=True,blank=True)
team_b = models.ForeignKey(Team,null=True,related_name='team_two',on_delete=models.DO_NOTHING)
team_b_score = models.PositiveIntegerField(null=True,blank=True)
team_won = models.ForeignKey(Team,null=True,related_name='team', on_delete=models.DO_NOTHING)

检查 if match 到 return 验证数据是不够的。你应该检查长度。因此,如果 len(match) == match_round - 1.

,您 return 验证数据

然而,您可以让数据库 return 不同值的数量,从而避免自己计算:

matches = Matchscore.objects.filter(
    gameevent=gameevent,
    <strong>match_round__range=(1, match_round)</strong>
).values('match_round').distinct().count()

if <strong>matches == match_round-1</strong>:
    return validated_data
else:
    raise serializers.ValidationError('Enter a valid match_round')