Как правильно вывести функцию book.user_max2(), чтобы сделать экспорт xlsx быстрым
При экспорте .xlsx функция book.user_max2() увеличивает нагрузку и засоряет оперативную память. Если просто взять book.price из модели, то такой проблемы нет. Но мне нужно, чтобы цена менялась при выгрузке, поэтому я написал функцию user_max2() в модели Products.
Все проблемы в функции user_max2(). Без нее все выгружается быстро и нет утечек памяти. Помогите пожалуйста, может кто-то уже сталкивался с этим.
модельные продукты
Другие модели
class Clients(models.Model):
STATUS_CHOICES = (
(0, ''),
(1, ''),
)
client_id = models.ForeignKey(ListUsers, on_delete=models.CASCADE, verbose_name='ID clients')
mf_id = models.IntegerField(verbose_name='ID brand')
k_up = models.FloatField(default=1, verbose_name='Markup to purchase price')
k_dn = models.FloatField(default=1, verbose_name='Sale price discount')
published = models.IntegerField(default=1, blank=True, choices=STATUS_CHOICES, verbose_name='')
updated = models.BooleanField(default=False, editable=False, blank=True, verbose_name='')
class Meta:
ordering = ('client_id',)
verbose_name = ''
verbose_name_plural = 'Individual discounts for the manufacturer'
unique_together = ('client_id', 'mf_id',)
def __str__(self):
return f'{self.client_id}'
class Brand(models.Model):
STATUS_CHOICES = (
(0, ''),
(1, ''),
)
brand_id = models.IntegerField(primary_key=True, db_index=True, unique=True, verbose_name='ID')
name = models.CharField(max_length=200, db_index=True, verbose_name='name')
slug = models.CharField(max_length=200, db_index=True, blank=True, verbose_name='URL')
clt1 = models.ManyToManyField(Clients, through="Brand2")
published = models.IntegerField(default=1, blank=True, choices=STATUS_CHOICES, verbose_name='')
updated = models.BooleanField(default=False, editable=False, blank=True, verbose_name='')
class Meta:
ordering = ('name',)
verbose_name = 'Brand'
verbose_name_plural = ''
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('brand', kwargs={'brand_id': self.pk})
class Brand2(models.Model):
STATUS_CHOICES = (
(0, ''),
(1, ''),
)
brand_id = models.ForeignKey(Brand, on_delete=models.CASCADE, verbose_name='ID brand')
clients_id = models.ForeignKey(Clients, on_delete=models.CASCADE, verbose_name='ID clients')
published = models.IntegerField(default=1, blank=True, choices=STATUS_CHOICES, verbose_name='')
updated = models.BooleanField(default=False, editable=False, blank=True, verbose_name='')
class Meta:
ordering = ('clients_id',)
verbose_name = 'Individual discounts for the manufacturer2'
verbose_name_plural = ''
unique_together = ('brand_id', 'clients_id')
def __str__(self):
return f'{self.clients_id}'
Просмотров
def export_excel(request):
products = (Product
.objects
.filter(stock__gt=0, published=True)
.select_related("brand", "product_sklad")
.prefetch_related("brand__clt1__client_id__discount_list_k1", "category__parent")
.exclude(product_sklad__gte=1)
)
headers = (
'Code', 'Article', 'Name', 'Manufacturer', 'Unit', 'Price', 'Remaining', 'Application',
'Normal vacation', 'New!')
data = tablib.Dataset( headers=headers, title="1212")
for book in products.iterator():
zayvka = ""
if book.artikul == "None":
book.artikul = ""
if book.brand == "None":
book.brand = ""
if book.new_product == 0:
book.new_product = ""
if book.stock > 50:
book.stock = ">50"
data.append((book.id_p, book.artikul, book.name, book.brand, book.shtuk_e, book.user_max2(),
book.stock, zayvka, book.min_kol, book.new_product))
with open("price_.xlsx", "wb") as f_price:
f_price.write(data.export('xlsx'))
f_price.close()
return HttpResponse('ok')