Как ускорить выгрузку?
Проблема в функции book.user_max2(), когда вызываю его в коде у меня начинает долго выгружаться прайс. А когда просто book.price то выгрузка моментальная. Помогите разобраться пожалуйста
models
class Clients(models.Model):
STATUS_CHOICES = (
(0, 'Не действует'),
(1, 'Действует'),
)
client_id = models.ForeignKey(ListUsers, on_delete=models.CASCADE, verbose_name='ID клиента')
mf_id = models.IntegerField(verbose_name='ID бренда')
k_up = models.FloatField(default=1, verbose_name='Наценка к цене закупа')
k_dn = models.FloatField(default=1, verbose_name='Скидка к цене продажи')
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 = 'Индивиуальная скидка на производителя1'
verbose_name_plural = 'Индивиуальные скидки на производителя1'
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='Наименование в своем прайсе')
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 = 'Бренд'
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 бренда')
clients_id = models.ForeignKey(Clients, on_delete=models.CASCADE, verbose_name='ID клиента')
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 = 'Индивиуальная скидка на производителя2'
verbose_name_plural = 'Индивиуальные скидки на производителя2'
unique_together = ('brand_id', 'clients_id')
def __str__(self):
return f'{self.clients_id}'
class Product(models.Model):
STATUS_CHOICES = (
(0, 'Не опубликовано'),
(1, 'Опубликовано'),
)
STATUS_NEW = (
(0, 'Нет'),
(1, 'Да'),
)
id_p = models.BigIntegerField(primary_key=True, db_index=True, unique=True, verbose_name='ID продукта')
artikul = models.CharField(max_length=200, db_index=True, blank=True, verbose_name='Артикул')
brend = models.CharField(max_length=200, db_index=True, blank=True, verbose_name='Бренд для поиска')
analog = models.CharField(max_length=500, blank=True, verbose_name='Аналоги артикула')
category = models.ManyToManyField(Category, blank=True, related_name='categ', verbose_name='Категория')
brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='Бренд')
product_sklad = models.ForeignKey(Sklad, on_delete=models.CASCADE, default=1, verbose_name='ID поставщика')
product_time = models.IntegerField(default=0, verbose_name='Срок доставки ( дн.)')
name = models.CharField(max_length=200, blank=True, verbose_name='Название продукции')
description = models.TextField(blank=True, verbose_name='Описание')
price = models.FloatField( verbose_name="Цена")
zakup = models.FloatField(default=price, blank=True,verbose_name="Цена закупа")
discount_product_min = models.FloatField(default=0,
verbose_name='Минимальный коэффициент скидки')
price_magazin = models.FloatField( default=0, blank=True, verbose_name="Минимальная розничная цена")
upakovka_f = models.CharField(max_length=200, blank=True, verbose_name='Упаковка',
help_text="Сколько единиц товара в упаковке")
shtuk_e = models.CharField(blank=True, max_length=50, verbose_name='Еденица измерения',
help_text="шт, компл, литр и т д ")
stock = models.PositiveIntegerField(default=0, verbose_name='Остаток на складе')
stock_k13 = models.PositiveIntegerField(default=0, verbose_name='Количество товара в пути', blank=True)
min_kol = models.IntegerField(default=1, db_index=True, verbose_name='Минимальное количество для покупки')
new_product = models.IntegerField(default=0, choices=STATUS_NEW, verbose_name='Новинка')
da_product = models.CharField(max_length=20, default=0, blank=True, verbose_name='Дата поступления')
published = models.IntegerField(default=1, blank=True, choices=STATUS_CHOICES, verbose_name='опубликован')
updated = models.BooleanField(default=False, editable=False, blank=True, verbose_name='Обновляется')
def user_max2(self):
user = get_current_user()
user_k = user.usrid.discount_list_k1.group_discount_list_k
listusers_id = user.usrid.listusers_id
brand2 = self.brand.clt1.all()
for pr in brand2:
if pr.published == 1:
if pr.mf_id == self.brand.brand_id and pr.client_id.listusers_id == listusers_id:
if pr.k_dn == 1:
return self.zakup * pr.k_up
else:
user_max = max(pr.k_dn, self.discount_product_min)
return self.price * user_max
user_max = max(user_k, self.discount_product_min)
return self.price * user_max
class Salenban(models.Model):
STATUS_CHOICES = (
(0, 'Не действует'),
(1, 'Действует'),
)
client_id = models.ForeignKey(ListUsers, on_delete=models.CASCADE, verbose_name='ID клиента')
mf_un = models.ForeignKey(Brand, on_delete=models.CASCADE, verbose_name='ID бренда')
updated = models.BooleanField(default=False, editable=False, blank=True, verbose_name='Обновляется')
published = models.IntegerField(default=1, blank=True, choices=STATUS_CHOICES, verbose_name='Опубликован')
class Meta:
ordering = ('client_id',)
verbose_name = 'Клиентские ограничения на бренд'
verbose_name_plural = 'Клиентские органичения на бренд'
unique_together = ('client_id', 'mf_un', )
def __str__(self):
return f'{self.published}'
views
@sync_to_async
@login_required
def export_excel(request):
chars = 'abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
number = int(10)
length = int(10)
for n in range(number):
password = ''
for i in range(length):
password += random.choice(chars)
pricesecret = Price.objects.get(id=1)
path = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + ""
path2 = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv"
path3 = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/rar"
path4 = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/xlsx"
try:
os.makedirs(path)
os.makedirs(path2)
os.makedirs(path3)
os.makedirs(path4)
except:
path = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + ""
path2 = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv"
path3 = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/rar"
path4 = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/xlsx"
xlsxpathname = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/xlsx")
zippathname = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv")
if xlsxpathname:
xlsxpathname = ''.join(map(str, xlsxpathname))
filepath = '/var/www/django/mysite/static/media/pricenew/' + str(request.user.usrid.listusers_id) + '/xlsx/' + xlsxpathname
if zippathname:
zippathname = ''.join(map(str, zippathname))
filepath4 = '/var/www/django/mysite/static/media/pricenew/' + str(request.user.usrid.listusers_id) + '/csv/' + zippathname
filepath2 = '/var/www/django/mysite/static/media/pricenew/' + str(request.user.usrid.listusers_id) + '/rar/' + pricesecret.url + '.lock'
if os.path.exists(filepath2) and os.path.exists(filepath) and os.stat(filepath).st_size != 0 and os.stat(filepath4).st_size != 0:
url = "https://localhost/media/pricenew/" + str(
request.user.usrid.listusers_id) + "/csv/" + zippathname
return JsonResponse({'pricesecret': zippathname, 'url': url,})
else:
files = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/rar/")
files2 = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/xlsx/")
files3 = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv/")
if files:
onlyfiles3 = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/rar/")
onlyfiles3 = ''.join(map(str, onlyfiles3))
eawa3 = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/rar/"
os.remove(eawa3 + onlyfiles3)
if files2:
onlyfiles1 = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/xlsx/")
onlyfiles1 = ''.join(map(str, onlyfiles1))
eawa = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/xlsx/"
os.remove(eawa + onlyfiles1)
if files3:
onlyfiles2 = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv/")
onlyfiles2 = ''.join(map(str, onlyfiles2))
eawa2 = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv/"
os.remove(eawa2 + onlyfiles2)
file_lock = open(filepath2, "wb")
price_title = "Прайс_" + datetime.today().strftime('%Y-%m-%d %H:%M')
saleban = (Salenban
.objects
.filter(client_id=request.user.usrid.listusers_id, published=1)
.select_related("client_id", "mf_un")
.prefetch_related("client_id__discount_list_k1")
.values_list("mf_un", flat=True).iterator()
)
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)
)
if saleban:
products = products.exclude(brand__in=saleban).iterator()
else:
products = products.iterator()
headers = [
"Код",
"Артикул",
"Наименование",
"Производитель",
"Ед",
"Цена,руб",
"Остаток",
"Заявка",
"Норма отпуска",
"Новинка!"
]
with open("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv/price_" + password + ".tmp", "w", encoding="utf-8", newline="" ) as f_price:
writer = csv.writer(f_price)
writer.writerow(headers)
for book in products:
writer.writerow([
book.id_p,
"" if book.artikul == "None" else book.artikul,
book.name,
"" if book.brand == "None" else book.brand,
book.shtuk_e,
book.user_max2(),
">50" if book.stock > 50 else book.stock,
"",
book.min_kol,
"" if book.new_product == 0 else book.new_product
])
os.rename("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv/price_" + password + ".tmp", "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv/price_" + password + ".csv")
read_file = pd.read_csv('/var/www/django/mysite/static/media/pricenew/' + str(request.user.usrid.listusers_id) + '/csv/price_' + password + '.csv')
read_file.to_excel('/var/www/django/mysite/static/media/pricenew/' + str(request.user.usrid.listusers_id) + '/xlsx/price_' + password + '.xlsx', index=None, sheet_name="Прайс АО ДАРС", header=True)
#os.remove("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/csv/price.csv")
url = "https://localhost/media/pricenew/" + str(
request.user.usrid.listusers_id) + "/xlsx/price_" + password + ".csv"
return JsonResponse({'pricesecret': password + ".csv", 'url': url})