我正在使用 Django 的通用关系来定义问答模型的投票模型。
这是我的投票模型:
模型.py
class Vote(models.Model):
user_voted = models.ForeignKey(MyUser)
is_upvote = models.BooleanField(default=True)
# Generic foreign key
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = ('content_type', 'user_voted')
视图.py
user_voted = MyUser.objects.get(id=request.user.id)
object_type = request.POST.get('object_type')
object = None;
if object_type == 'question':
object = get_object_or_404(Question, id=self.kwargs['pk'])
elif object_type == 'answer':
object = get_object_or_404(Answer, id=self.kwargs['pk'])
# THIS LAST LINE GIVES ME THE ERROR
vote, created = Vote.objects.get_or_create(user_voted=user_voted, content_object=object)
然后我得到这个错误:
FieldError at /1/
Cannot resolve keyword 'content_object' into field. Choices are: answer, content_type, id, is_upvote, object_id, question, user_voted
当我将“对象”打印到 Django 控制台时,它会打印“问题 1”对象。所以我不明白为什么“content_object = object”行给了我字段错误......
有任何想法吗 :(((???
谢谢