我有一个名为"following"的模型,其中一个用户可以使用Django rest框架跟随另一个用户。我正在尝试实现一个验证,这样你就不会跟踪某人两次,并尝试内置的UniqueTogetherValidator。
以下是我的模型的相关部分.py
class Following(models.Model):
user = models.ForeignKey('User', related_name='user', on_delete=models.CASCADE)
follower = models.ForeignKey('User', related_name='follower', on_delete=models.CASCADE)
和serializers.py:
class FollowingSerializer(serializers.HyperlinkedModelSerializer):
user = serializers.CharField(source='user.username')
follower = serializers.CharField(source='follower.username')
class Meta:
model = Following
fields = ['user', 'follower']
validators = UniqueTogetherValidator(
queryset = Following.objects.all(),
fields = ['user', 'follower'],
message = "You are already following that person!"
)
我有一些现有的数据:
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"user": "mike",
"follower": "chelsea"
},
{
"user": "mike",
"follower": "chloe"
}
]
}
当我尝试使用API接口添加任何新的以下对象时,我会得到以下错误:
TypeError at /followings/
'UniqueTogetherValidator' object is not iterable
Request Method: POST
Request URL: http://127.0.0.1:8000/followings/
Django Version: 3.0.5
Exception Type: TypeError
Exception Value:
'UniqueTogetherValidator' object is not iterable
...
我哪里错了?提前感谢!
如中所述https://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidatorMeta
下的validators
变量应该是一个列表,
你的代码应该是
class FollowingSerializer(serializers.HyperlinkedModelSerializer):
user = serializers.CharField(source='user.username')
follower = serializers.CharField(source='follower.username')
class Meta:
model = Following
fields = ['user', 'follower']
validators = [
UniqueTogetherValidator(
queryset = Following.objects.all(),
fields = ['user', 'follower'],
message = "You are already following that person!"
)
]