Django获取Comment对象时如何获取外键commentGroup的commentGroupDesc字段
如何从外键对象中获取commentGroupDesc字段?
我需要从Comment模型的外键关联对象中获取commentGroupDesc字段,目前已经能正常获取到commentGroup,但需要该字段值用于表单填充。
相关代码
models.py
class commentGroup (models.Model): commentGroup = models.CharField(_("commentGroup"), primary_key=True, max_length=255) commentGroupDesc = models.CharField(_("commentGroupDesc"),null=True, blank=True, max_length=255) def __str__(self): return str(self.commentGroup) class Meta: ordering = ['commentGroup'] class Comment (models.Model): commentID = models.AutoField(_("commentID"),primary_key=True) commentUser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) commentGroup = models.ForeignKey(commentGroup, on_delete=models.CASCADE, null=True) commentCI = models.ForeignKey(Servicenow, on_delete=models.CASCADE, null=True) commentText = RichTextField(_("commentText"), null=True, blank=True) commentTableUpdated = models.CharField(_("commentTableUpdated"), null=True, blank=True, max_length=25) def __str__(self): return str(self.commentGroup) class Meta: ordering = ['commentGroup']
views.py
comment = Comment.objects.get(pk=commentID)
解决方案
comment作为Comment的实例,它的commentGroup属性直接指向关联的commentGroup对象,通过链式访问即可拿到目标字段:
# 确认comment.commentGroup不为空时直接获取 comment_group_desc = comment.commentGroup.commentGroupDesc # 若commentGroup可能为null,为避免触发AttributeError,可做空值判断 comment_group_desc = comment.commentGroup.commentGroupDesc if comment.commentGroup else "" # 或者用getattr处理默认值 comment_group_desc = getattr(comment.commentGroup, 'commentGroupDesc', "")
拿到该字段值后即可直接用于表单填充。
内容的提问来源于stack exchange,提问作者user625079
相关产品推荐
相关产品推荐

