为什么target_dialogue始终为None?
型号:
class Dialogue(models.Model):
name = models.CharField(max_length=30, blank=True)
is_conference = models.BooleanField(default=False)
participants = models.ManyToManyField(
Person,
related_name='dialogues',
)
def __str__(self):
return self.name or str(self.pk)
并且在视野中我希望得到适当的对话,其中包含参与者字段2对象 - 用户和伴侣。如果这个对话不存在,我就创建它:
target_dialogue = None
try:
target_dialogue = Dialogue.objects.get(is_conference=False,participants__in=[user, companion])
except ObjectDoesNotExist:
target_dialogue = Dialogue()
target_dialogue.save()
target_dialogue.participants.add(user)
target_dialogue.participants.add(companion)
finally:
return render(request, 'dialogues/dialogue.html', {
'dialogue': target_dialogue,
})
但target_dialogue始终为None。这是什么原因?我本来应该解决从db获取对话的麻烦,以便过滤器参数不好,但现在我对它有所怀疑。也许别的什么?
答案 0 :(得分:0)
request.user
不是Person
模型的对象,您在对话中拥有该关系。
您必须先获取人物对象:
user = Person.objecs.get(user=request.user). # According to your person model
跟随同伴,然后查询:
target_dialogues = Dialogue.objects.filter(is_conference=False,participants__in=[user,companion]