Choose queryset for limit_choices_to based on object fields

谁说胖子不能爱 提交于 2020-01-11 12:04:51

问题


I am trying to limit the choices of a foreign field to those other objects who look like the object self.

I've tried this:

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()

but I get the error

_filter_or_exclude() argument after ** must be a mapping, not str

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.

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}

nor

limit_choices_to=lambda: {'number': number}

I am using Django 1.7.


回答1:


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()


来源:https://stackoverflow.com/questions/22597521/choose-queryset-for-limit-choices-to-based-on-object-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!