基于Django管理页面中另一个字段的过滤列表框

时间:2014-02-03 02:07:31

标签: django django-admin

我正在Django网站上展示有关股票市场证券的信息。它有一个这样的模型:

class Market(models.Model):
    name = models.CharField(max_length=255)

class Security(models.Model):
    name = models.CharField(max_length=255)
    market = models.ForeignKey(Market)

class SecurityGroup(models.Model):
    name = models.CharField(max_length=255)
    market = models.ForeignKey(Market)
    securities = models.ManyToManyField(Security)

问题是我们的数据库中有大约100个市场,每个市场可以包含500多个证券。当您在Django管理面板中创建新的SecurityGroup实例时,显示列表框需要很长时间,因为它可以包含数万个项目。当我创建一个新的SecurityGroup时,我想做的是这样的事情:

  1. 用户输入群组名称并选择市场
  2. 证券清单框被过滤以仅显示来自所选市场的证券
  3. Django有可能吗?

1 个答案:

答案 0 :(得分:2)

类似这样的事情

class AdminSecurityGroup(admin.ModelAdmin):        
    object = None
    def get_object(self, request, object_id):
       self.object = super(AdminSecurityGroup, self).get_object(request, object_id)
       return self.object

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name.lower() == 'securities':
           if self.object and self.object.market:
              kwargs['queryset'] = Security.objects.filter(market=self.object.market)
           else:
              kwargs['queryset'] = EmptyQuerySet()
        return super(AdminSecurityGroup, self).formfield_for_manytomany(db_field, request, **kwargs)

你还需要改变

securities = models.ManyToManyField(Security, blank=True)

并分两步保存模型