django - django select_related 无法解析关键字
问题描述
我正在尝试在 django 中优化我的 ORM 查询。我使用 connection.queries 来查看 django 为我生成的查询。
假设我有这些模型:
class Template_folder(models.Model):
tf_id = models.AutoField(primary_key=True)
tf_foldername = models.TextField(max_length=100)
tf_parent = models.IntegerField()
tf_seq = models.IntegerField()
tf_sorter = models.TextField()
class Meta:
db_table = 'template_folder'
class Templateforein(models.Model):
tp_id = models.AutoField(primary_key=True)
tp_idfolder = models.ForeignKey(Template_folder, to_field='tf_id', db_column='tp_idfolder')
tp_title = models.TextField(max_length=45)
tp_contents = models.TextField()
tp_created = models.DateTimeField(default=timezone.now)
tp_updated = models.DateTimeField(default=timezone.now)
tp_iduser = models.IntegerField()
class Meta:
db_table = 'template'
所以我应该使用:
template = Templateforein.objects.select_related().filter(Q(tf_id=tp_idfolder) | Q(tf_parent=tp_idfolder))
我必须使用 template_folder 模型。
错误内容:
django.core.exceptions.FieldError: Cannot resolve keyword 'tf_id'
into field. Choices are: tp_choice, tp_confolderid, tp_contents,
tp_created, tp_flowid, tp_id, tp_idfolder, tp_idfolder_id, tp_iduser,
tp_pagenum, tp_title, tp_updated
我认为您应该使用模板模型。我应该使用 template_folder 模型。如何使用 template_folder 挂起过滤器?
解决方案
您想要做的是进行跨越关系的查找,例如
MyObject.objects.filter(myforeignkeyfieldname__id=id)
推荐阅读
- java - 尝试在 Jpanel 中添加 ScrollPane,在 BorderLayout 中使用空布局
- ruby-on-rails - 如何在数组上使用 searchkick 搜索方法
- command-line-interface - spacy CLI 训练 NER 中的 AssertionError
- ios - Realm 强制在定义动态变量时添加@objc 词
- python - 使用 Pymongo 提取 MongoDB 中最新文档的时间戳
- javascript - 将导航栏/箭头导航与滚动同步
- python - 附加操作按钮在烧瓶管理员上不起作用
- python - 所有文本都保存在一行中
- firebase - 我想一次性将用户联系人同步到 Firebase Firestore
- php - 我的 php 脚本未解密 Sagepay Form 3.00 版中的返回 crypt