gpt4 book ai didi

Django REST Framework - 嵌套序列化程序验证?

转载 作者:行者123 更新时间:2023-12-03 14:57:32 24 4
gpt4 key购买 nike

所以我有这样的模型:

class Leaderboard(models.Model):
pass


class Column(models.Model):
leaderboard = models.ForeignKey(Leaderboard, related_name="columns", on_delete=models.CASCADE)
related_columns = models.ManyToManyField(self)
index = models.PositiveIntegerField()

像这样的序列化器:
class ColumnSerializer(ModelSerializer):
related_columns = serializers.PrimaryKeyRelatedField(queryset=Column.objects.all(), many=True)

class Meta:
model = Column
fields = ('leaderboard', 'related_columns', 'index',)


class LeaderboardSerializer(ModelSerializer):
children = ColumnSerializer(many=True)

class Meta:
model = Leaderboard
fields = ('columns',)

所以我想做的是验证添加到 related_columns 的任何列为 ColumnSerializer已经属于它的 Leaderboard parent 。在创建 id 期间,我曾多次尝试访问排行榜或排行榜 ID(例如通过在字段中手动指定 ColumnSerializer)。进行验证,但 LeaderboardSerializer 未在 Column 之前初始化,因此我无法验证详细信息。

基本上,我想修改 queryset=Column.objects.all()成为 queryset=self.instance.leaderboard.columns.all()
但是我无权访问 LeaderboardColumn .例如,如果我访问 self.parent.instance/initialColumnSerializer它是 None直到里面 Leaderboard.validate_columns() .我想到的一件事是只在排行榜方面进行验证,但我仍然认为在 Column 内进行此验证应该是“可行的”。以防我想直接编辑那些,而无需先通过 Leaderboard ...

最佳答案

这是我解决这个问题的方法:

def validate_columns(self, columns):
if not columns:
raise serializers.ValidationError("Leaderboards require at least 1 column")

# Make sure all column indexes are unique
indexes = [column['index'] for column in columns]
if len(set(indexes)) != len(columns):
raise serializers.ValidationError("Columns must have unique indexes!")

# Make sure all column keys are unique
keys = [column["key"] for column in columns]
if len(set(keys)) != len(columns):
raise serializers.ValidationError("Columns must have unique keys!")

# Validate that column.computation_indexes points to valid columns
for column in columns:
if 'computation_indexes' in column and column['computation_indexes']:
for index in column['computation_indexes'].split(","):
try:
if int(index) not in indexes:
raise serializers.ValidationError(f"Column index {index} does not exist in available indexes {indexes}")
except ValueError:
raise serializers.ValidationError(f"Bad value for index, should be an integer but received: {index}.")

return columns

我确保这些列是唯一的(在它们的键和索引中)并且它们引用的列也存在。

关于Django REST Framework - 嵌套序列化程序验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48465115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com