【问题标题】:Override field arguments in inherited django models覆盖继承的 Django 模型中的字段参数
【发布时间】:2014-11-28 21:21:21
【问题描述】:

我安装了一个 django 应用程序并想限制外键的选择:

class InstalledModel(models.Model):
    ...
    base_field = models.ForeignKey(AnotherModel)

class MyModel(InstalledModel):
    """
    Somehow use limit_choices_to in base_field
    """

我知道字段不能在继承模型中更改,但想知道这是否也适用于它的参数,因为它似乎不会改变模型本身的序列化和初始化。

【问题讨论】:

  • 不会使用models.ForeignKey(AnotherModel) 工作吗?但是让它们保持松散耦合。
  • 它可以工作,但它允许您从 AnotherModel 的所有实例中进行选择,我只想限制为某些实例。
  • Field.choices 怎么样?它们可以是动态的,但不推荐使用。
  • 也可以,问题是我似乎无法在 MyModel 中设置它,因为它是从 InstalledModel 继承的。

标签: django python-3.x django-models


【解决方案1】:

您可以尝试使用属性作为limit_choices_to 参数,例如:

class InstalledModel(models.Model):
    @property    
    def another_model_choices(self):
        if isinstance(self, MyModel):
            return {'some_condition': True}
        return None

    base_field = models.ForeignKey(AnotherModel, limit_choices_to=another_model_choices)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多