内联实例的多个查询Django admin

时间:2018-11-20 12:03:26

标签: django python-3.x django-models django-forms django-admin

我为我的一个模型创建了一个自定义Admin。并添加了一个关系表作为其内联之一。

1)。现在的事情是,Inline有超过100行。内联还具有其他模型的外键对象。

2)。每当我加载模型表格时,它都会花费大量时间来加载。

3)。我调试并检查了查询的代码和数量。没有重复的查询,并且计数是名义上的。

4)。我已经覆盖了内联实例的查询集,以预取其外键实例。

5)。我继续进行,并在表单集的原始代码中提出了一个随机验证错误。

6)。我发现错误发生时,每个内联实例都有一个不同的查询。假设它有100行,则对该内联重复查询100次。

7)。有什么方法可以预取或优化此方案,因为它导致应用程序太滞后了

这是代码:

#model
class MyModel(models.Model):

user = models.ForeignKey(User, on_delete=models.CASCADE)
phone_number = models.CharField(max_length=10)
entity1 = models.ForeignKey("entities.entity1", null=True, blank=True, on_delete=models.CASCADE)
entity2 = models.ForeignKey("entities.entity2", null=True, blank=True, on_delete=models.CASCADE)
is_disabled = models.BooleanField(default=False)
name = models.CharField(max_length=24, blank=True, null=True)

class Meta:
    db_table = 'my_model'

def __str__(self):
    return "{}:{}".format(self.phone_number, self.entity2)


#admin
class Entity2Admin(admin.GeoModelAdmin, VersionAdmin):
list_filter = ('data_status')
readonly_fields = ('source', 'batch','is_live', )
exclude = ('search_key', 'live_at', 'qc_approved_at')

    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)

        for obj in formset.deleted_objects:
            obj.delete()

        for instance in instances:
            if isinstance(instance, MyModel):
                if (not instance.created_by):
                    instance.created_by = request.user
                if (not instance.id):
                    instance.some_field = some_value
            instance.save()
        formset.save_m2m()

inlines = [MyModelInline]

extra_js = ['js/admin/GoogleMap.js','https://maps.googleapis.com/maps/api/js?key=AIzaSyA-5gVhxxxxxxxxxxxxxxxxxxxxxxx&callback=initGoogleMap']


#MyModelInline
class MyModelInline(admin.TabularInline):
model = MyModel
extra = 0
can_delete = True
show_change_link = False
formset = MyModelFormSet
readonly_fields = ['user']
verbose_name_plural = "MyModels"
fields = ['phone_number', 'name', 'user', 'entity2']

def get_queryset(self, request):
    return super(MyModelInline, self).get_queryset(request).select_related('entity2', 'user')

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "entity2":
        object_id = request.resolver_match.kwargs.get('object_id')
        kwargs["queryset"] = Entity2.objects.filter(field=value)
    return super().formfield_for_foreignkey(db_field, request, **kwargs)

请帮助

0 个答案:

没有答案