Django为models.ForeignKey生成太多SQL查询

2024-09-29 23:17:07 发布

您现在位置:Python中文网/ 问答频道 /正文

一个模型类有一个外键(models.ForeignKey),它引用另一个模型

Django为此外键生成太多SQL查询。当一个admin.stackedLine类使用模型类时,它会尝试创建一个包含引用表中所有项目的选择列表(下面的示例代码中为ProductTemplate

是否有办法将外键限制为仅列出一项,而不是引用表中的所有项

任何其他建议也将受到高度赞赏。如果你需要更多的细节,请告诉我

In file admin.py:
...
class TransactionAttributeInlineAttribute(admin.StackedInline):
    model = models.TransactionAttribute
    verbose_name = 'Transaction Link'
    verbose_name_plural = 'Product Links'
class MyAttributeAdmin(admin.ModelAdmin):
    inlines = [TransactionAttributeInlineAttribute]
    list_display = ['name','datatype','required']
...


In file models.py:
...
class TransactionAttribute(models.Model):
    product_template = models.ForeignKey(ProductTemplate)
...

Tags: djangonameinpy模型verboseadminmodels
1条回答
网友
1楼 · 发布于 2024-09-29 23:17:07

对于foreign key,Django默认生成一个下拉选择小部件,其中包含引用表中的所有项,不仅包括链接项,还包括所有其他无关项

在我的例子中,这种行为产生了太多的SQL查询,使数据库不知所措。修复方法是取消下拉选择,并限制Django仅显示外键的链接项

原始\u id\u字段=['product\u template']

请参阅以下链接的更多讨论: https://forum.djangoproject.com/t/models-foreignkey-caused-too-many-sql-queries/1649/5?u=simpleopen

修复程序的代码更改:

class TransactionAttributeInlineAttribute(admin.StackedInline):
    model = models.TransactionAttribute
    raw_id_fields = ['product_template']
    verbose_name = 'Transaction Link'
    verbose_name_plural = 'Product Links'

相关问题 更多 >

    热门问题