0

请我如何使用 post_export 信号更新下面的导出公司模型。我不想导出以前未导出的项目。所以最好的事情是使用信号。

但是,如果我在下面代码末尾的信号中打印模型,我会得到一个类型类,例如<class 'app.models.Company'>

我知道保存模型做错了,但找不到我的路。

也许我不了解此处django-import-export找到的库文档。

模型.py

class Company(models.Model):
    class Meta:
        verbose_name_plural = "Companies"

    company_name = models.CharField(max_length=254, blank=True)
    website = models.URLField(max_length=254, unique=True)
    address = models.CharField(max_length=254, blank=True, null=True)
    imported = models.BooleanField(default=False)
    exported = models.BooleanField(default=False)
    user = models.ForeignKey(User)

    def __str__(self):
        if self.company_name:
            return self.company_name
        return self.domain

管理员.py

from django.dispatch import receiver 
from import_export.signals import post_import, post_export

class CompanyResource(resources.ModelResource):
    class Meta:
        model = Company
        fields = ('website', 'user', 'country', 'source', 'industry')

@admin.register(Company)
class CompanyAmin(ImportExportModelAdmin):
    resource_class = CompanyResource
    list_display = ('domain', 'website', 'exported', 'added_on')
    list_filter = ('user', 'country', 'imported', 'exported', 'added_on')


@receiver(post_export, dispatch_uid='ss1')
def _post_export(model, **kwargs):
    print(model) 
    model.exported = True
    model.save() # This line when included raises Error: "save() missing 1 required positional argument: 'self'" so code breaks here
4

2 回答 2

1

Арсений Краснов 解决方案有问题,在导出之前更新模型而不是之后。

要在之后导出,您必须在 resources.ModelResource 中添加以下函数

class CompanyResource(resources.ModelResource):
    class Meta:
        model = Company
        fields = ('website', 'user', 'country', 'source', 'industry')

    def after_export(self, queryset, data, *args, **kwargs):
        queryset.update(exported=True)
于 2018-03-20T00:05:37.547 回答
1

https://docs.djangoproject.com/en/1.11/topics/signals/#connecting-receiver-functions

请注意,该函数采用 sender 参数以及通配符关键字参数 (**kwargs);所有信号处理程序都必须采用这些参数。

@receiver(post_export, dispatch_uid='ss1')
def _post_export(sender, model, **kwargs):
    model.exported = True
    model.save()

更新:django-import-export 不要在信号中发送导出的查询集

所以你可以在 ModelAdmin 中覆盖 export_action

@admin.register(Company)
class CompanyAmin(ImportExportModelAdmin):
    resource_class = CompanyResource
    list_display = ('domain', 'website', 'exported', 'added_on')
    list_filter = ('user', 'country', 'imported', 'exported', 'added_on')

    def export_action(self, request, *args, **kwargs):
        response = super().export_action(request, *args, **kwargs)
        qs = self.get_export_queryset(request)
        qs.update(exported=True)
        return response
于 2017-10-10T12:14:02.760 回答