我正在使用我不熟悉的 Django REST 框架制作市场应用程序。
我写了一个测试来测试 unique together 字段。它按我想要的方式工作,当字段 author 和 target 不是唯一在一起时引发 UNIQUE constraint failed 错误,但我的问题是我应该如何处理这个错误以便我的测试通过。
models.py
class Review(models.Model):
FEEDBACK_CHOICES = [
('POSITIVE', 'positive'),
('NEUTRAL', 'neutral'),
('NEGATIVE', 'negative')
]
feedback = models.CharField(
max_length=8,
choices=FEEDBACK_CHOICES,
default='NEGATIVE'
)
review = models.TextField(max_length=200)
target = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='reviews',
on_delete=models.CASCADE
)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='given_reviews',
on_delete=models.CASCADE
)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['created']
unique_together = ['author', 'target']
serializers.py
class ReviewSerializer(serializers.ModelSerializer):
target = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all()
)
author = serializers.ReadOnlyField(source='author.id')
class Meta:
model = Review
fields = [
'id',
'feedback',
'review',
'target',
'author',
'created'
]
views.py
class ReviewViewSet(viewsets.ModelViewSet):
queryset = Review.objects.all()
serializer_class = ReviewSerializer
permission_classes = [
ReviewPermissions
]
def perform_create(self, serializer):
serializer.save(author=self.request.user)
MMMHUHU
相关分类