根据对象字段为 limit_choices_to 选择查询集 [英] Choose queryset for limit_choices_to based on object fields
问题描述
我试图将外部字段的选择限制为那些看起来像对象自身的其他对象.
I am trying to limit the choices of a foreign field to those other objects who look like the object self.
我已经试过了:
class Model1(models.Model):
entry = models.ForeignKey(Model2, limit_choices_to='get_limit_choices_to')
number = IntegerField()
def get_limit_choices_to(self):
return Model2.objects.filter(expenditure_type=self.expenditure_type)
class Model2(models.Model):
number = IntegerField()
但我收到错误
_filter_or_exclude() argument after ** must be a mapping, not str
我不知道 limit_choices_to 是否是正确的方法.也许我应该选择 a 中的查询集或视图.
I don't know if limit_choices_to is the right way to do this. Maybe I should choose the queryset in a or the views.
错误表明 limit_choices_to='get_limit_choices_to'
是一种错误的引用方法的方式,但是我该如何正确引用该方法呢?我不能用
The error says that limit_choices_to='get_limit_choices_to'
is a wrong way to refer to the method, but how can I refer to the method correctly? I can't use
limit_choices_to=lambda: {'model1_set': self}
也没有
limit_choices_to=lambda: {'number': number}
我使用的是 Django 1.7.
I am using Django 1.7.
推荐答案
你的函数应该在模型之前.并且应该返回一个字典
Your function should be before the model. And should return an dictionary
def get_limit_choices_to():
return {'entry': Model2.objects.get(number=1).id}
class Model1(models.Model):
entry = models.ForeignKey(Model2, limit_choices_to=get_limit_choices_to)
number = IntegerField()
class Model2(models.Model):
number = IntegerField()
这篇关于根据对象字段为 limit_choices_to 选择查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!