Products can be exported in excel format from the Product
table. But all the user's products are exported.
How can I export only request.user
's products?
Here is view :
def export_excel(request):
dataset = ProductResource().export()
response = HttpResponse(dataset.xlsx, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response["Content-Disposition"] = "attachment; filename=Products-" + str(datetime.datetime.now().date())+".xlsx"
return response
Here is resources.py :
class ProductResource(resources.ModelResource):
author = Field()
brand_id = Field()
class Meta:
model = Product
fields = ["id", "author", "brand_id", "name", "barcode", "unit"]
export_order = ["id", "author", "brand_id", "name", "barcode", "unit"]
def dehydrate_author(self, product: Product) -> str:
return f"{product.author.username}"
def dehydrate_brand_id(self, product: Product) -> str:
return f"{product.brand_id.name}"
It is easy to do, you can pass a queryset to export()
:
def export_excel(request):
# adjust as required
qs = Product.objects.filter(product__author__username=request.user.username)
dataset = ProductResource().export(qs)
# ...
return response
In case it helps, note also that import-export provides a UI interface for export via Admin integration.