用于limit_choices_to的Django抽象模型覆盖方法

时间:2016-02-03 17:08:49

标签: django inheritance model abstract-class

以下是我的模特:

class BudgetName(model.Models):
    name = models.CharField(max_length=150)
    type = models.IntegerField(default=0,choices=((0,'incomes'),(1,'outcomes')))

class FinancialModel(models.Models):
    class Meta:
        abstract = True

    def my_limit_choices():
        return None

    """ Here goes some price fields, not important here """
    budgetname = models.ForeignKey(BudgetName, limit_choices_to= my_limit_choices)

class Incomes(FinancialModel):
    def my_limit_choices():
        return {'type':0}

class Outcomes(FinancialModel):
    def my_limit_choices():
        return {'type':1}

它在抽象类中工作正常 - 当我尝试在my_limit_choices方法中过滤某些东西时。但是,似乎它们在子类中没有被覆盖。为什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

无法让limit_choices_to调用实例方法my_limit_choices

另一种方法是定义自定义模型表单,并在__init__方法中设置查询集。

class FinancialModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyOrderForm, self).__init__(*args, **kwargs)
        self.fields['budgetname'].queryset = BudgetName.objects.filter(**self.instance.my_limit_choices())

然后在模型管理员中使用此表单:

class IncomesAdmin(admin.ModelAdmin):
    form = FinancialModelForm

class OutcomesAdmin(admin.ModelAdmin):
    form = FinancialModelForm

admin.site.register(Incomes, IncomesAdmin)
admin.site.register(Outcomes, OutcomesAdmin)