You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django技术问询:子类重写ForeignKey的limit_choices_to,以及在通用关系抽象类中限制ContentType可选范围

Django技术问询:子类重写ForeignKey的limit_choices_to,以及在通用关系抽象类中限制ContentType可选范围

嘿,我最近跟着Django文档实现了一个抽象类GenericReferModel,用来定义和其他一个或多个模型的通用关系,目前一切都还算顺利。不过现在我遇到了个需求:想通过models.ForeignKey的limit_choices_to属性来限制ContentType的可选范围,而且希望这个抽象类的子类能方便地重写这个限制条件。

先贴一下我目前写的代码:

from typing import Any

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.translation import gettext_lazy as _

class GenericReferModel(models.Model):
    # 想让子类重写这个属性来定义ContentType的可选范围
    refer_type_choices: models.Q | dict[str, Any] | None = None

    # 通用关系的核心字段
    refer_type = models.ForeignKey(
        ContentType,
        on_delete=models.CASCADE,
        verbose_name=_("关联类型"),
        # 这里想动态引用refer_type_choices作为limit_choices_to的值
        # 直接写limit_choices_to=self.refer_type_choices显然不行,因为字段定义时还没有实例
        limit_choices_to=...
    )
    refer_id = models.PositiveIntegerField(_("关联ID"))
    refer_object = GenericForeignKey("refer_type", "refer_id")

    class Meta:
        abstract = True

我的想法是,子类继承这个抽象类后,只需要简单重写refer_type_choices这个类属性,就能自定义允许关联的ContentType范围,比如:

class MyReferModel(GenericReferModel):
    # 限制只能关联myapp下的article和comment模型
    refer_type_choices = models.Q(app_label='myapp', model__in=['article', 'comment'])

    # 其他自定义字段...

但现在卡在了怎么在抽象类的refer_type字段中动态使用refer_type_choices作为limit_choices_to的参数。如果每个子类都重新定义一遍refer_type字段,那抽象类的意义就打折扣了,有没有更优雅的实现方式呢?

备注:内容来源于stack exchange,提问作者browser-bug

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 02:44:46