我收到此错误: Cannot assign "[<Response: Response object>, <Response: Response object>]": "Comment.response" must be a "Response" instance
。如何通过匹配申请人和面试ID来为实例分配响应?
另外,我只想要来自objects.filter()
def post_comment(request, interview_id, applicant_id):
if request.POST:
text = str(request.POST['add_comment'])
interview = Interview.objects.get(id = interview_id)
applicant = Applicant.objects.get(id = applicant_id)
response = Response.objects.filter(interview = interview, applicant = applicant)
date = datetime.datetime.now()
comment = Comment(
user = request.user,
applicant = applicant,
interview = interview,
response = response,
comment = text,
created_at = date,
)
我的模型如下:
class Response(models.Model):
video_guid = models.CharField(max_length=32)
interview = models.ForeignKey(Interview)
applicant = models.ForeignKey(Applicant)
question = models.ForeignKey(Question)
class Comment(models.Model):
user = models.ForeignKey(User)
applicant = models.ForeignKey(Applicant)
interview = models.ForeignKey(Interview)
response = models.ForeignKey(Response)
comment = models.TextField(default='')
created_at = models.DateTimeField(default=datetime.datetime.now())
我是Django的新手:(非常感谢任何帮助!
答案 0 :(得分:2)
您遇到的问题是您的过滤器会返回多个结果;不只是“第一”或“最后”(因为你没有指定这样的条件)。
第二个问题是您的模型不允许每条评论有多个回复。
您有几个选择:
调整模型以允许每条评论有多个回复。为此,请将response = models.ForeignKey(Response)
更改为response = models.ManyToMany(Response)
(请参阅ManyToMany
),然后调整视图。首先创建一个Comment
对象,然后comment.response.add()
每个响应。
为每个响应条目创建多个comment
个对象。这可能不太理想;但它无需迁移数据库架构即可运行。
以下是它的外观:
for i in response:
Comment.objects.create(
user = request.user,
applicant = applicant,
interview = interview,
response = i,
comment = text,
created_at = date)
您的模型具有您不需要的冗余字段。由于Comment
与Response
有关系,因此您无需复制Response
模型中Comment
的字段。您可以follow relationships获取相关字段:
c = Comment.objects.get(pk=1)
c.response.interview # interview object
# Get all the comments for where the interview objects primary key is 1
c = Comment.objects.filter(response__interview__pk=1)
r = Response.objects.get(pk=1)
r.comment_set.all() # all comments for this response
在您坐下来编写模型之前,请记下您需要对数据库执行何种查询。这将帮助您确定需要哪些字段(以及哪些关系)。例如,现在没有办法获得特定访谈的“第一个”或“最后一个”响应(因为Response
中没有日期字段)。
答案 1 :(得分:1)
当您的查询Response.objects.filter(interview = interview, applicant = applicant)
返回list
且其中包含两个响应对象时,无法将其分配给Comment.response,这是响应的FK。
ForeignKey只能将引用(id)存储到其他表/模型的单个记录中。