我正在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
时,我想做的是这样的事情:
Django有可能吗?
答案 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)
并分两步保存模型