Python中文
首页
教程
问答
标签
搜索
登录
注册
Python获取GenericRelation对象
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我有以下代码:</p> <p><strong>数据/电话.py</strong>:</p> <pre><code>class TelephoneNumber(models.Model): MOBILE = 0 HOME = 1 TELEFON_CHOICES = ( (MOBILE, _("Mobile")), (HOME, _("Landline")), ) object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType) of = generic.GenericForeignKey('content_type', 'object_id' ) label = models.SmallIntegerField(choices=TELEFON_CHOICES) number = models.CharField(max_length=20, blank=True) </code></pre> <p><strong>模型.py</strong>:</p> ^{pr2}$ <p>不,我想提供这样一个功能来检索用户的每个电话号码:</p> <pre><code>def get_telnumbers(self): tellist = [] #print(self.telephonenumbers.all()) for tel in self.telephonenumbers.all(): tellist.append(tel) return tellist </code></pre> <p>问题是,线路<code>print(self.telephonenumbers.all())</code>不打印任何电话号码,即使已经提供了很多电话号码。 返回的dict也是空的。在</p> <p>如何访问保存在<code>Staff</code>上下文中的GenericRelation对象?在</p> <p><strong>编辑:</strong></p> <p>以下代码:</p> <pre><code>for tel in TelephoneNumber.objects.all(): print(tel) print(tel.of) </code></pre> <p>给我保存的每个电话号码,并通过<code>tel.of</code>找到电话号码所属的正确员工用户。在</p> <p>那么,为什么<code>self.telephonenumbers.all()</code>不能正常工作(<code>self.user</code>还返回应该为其保存电话号码的正确用户)?在</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>确保在创建新的<code>TelephoneNumber</code>对象时,提供<code>content_object</code>属性作为相应的<code>Staff</code>对象</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
jupyter运行一个旧的pytorch版本
6 回答
Jupyter运行不同版本的卸载库?
5 回答
Jupyter运行指定的键盘快捷键
1 回答
Jupyter通过.local文件“逃逸”virtualenv。我该如何缓解这种情况?
3 回答
Jupyter重新加载自定义样式
10 回答
Jupyter错误:“没有名为Jupyter_core.paths的模块”
6 回答
jupyter错误:无法在随机林中将决策树视为png
10 回答
Jupyter错误'内核似乎已经死亡,它将自动重新启动'为一个给定的代码块
10 回答
Jupyter错误地用阿拉伯语和字母数字元素显示Python列表
9 回答
Jupyter隐藏数据帧索引,但保留原始样式
3 回答
Jupyter集线器:启动器中出现致命错误。。。系统找不到指定的文件
5 回答
Jupyther中相同值的相同哈希,但导出到Bigquery时不相同
7 回答
Jupy上Python的读/写访问问题
4 回答
jupy上没有模块cv
2 回答
Jupy上的排序错误
10 回答
Jupy中bqplot图形的紧凑布局
7 回答
Jupy中matplotlib plot的连续更新
1 回答
Jupy中Numpy函数的文档
1 回答
Jupy中Pandas的自动完成问题
7 回答
jupy中Qt后端的Matplotlib动画
2 回答