首页 > 解决方案 > 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 挂起过滤器?

标签: djangodjango-modelsdjango-rest-framework

解决方案


您想要做的是进行跨越关系的查找,例如

MyObject.objects.filter(myforeignkeyfieldname__id=id)

推荐阅读