Неудачный тестовый пример Django: функция не возвращает ожидаемую сумму связанных полей моделиPython

Программы на Python
Anonymous
Неудачный тестовый пример Django: функция не возвращает ожидаемую сумму связанных полей модели

Сообщение Anonymous »

Я работаю с Django 4.2.2, и у меня есть тестовый пример, который не удался, поскольку пользовательская функция не возвращает ожидаемую сумму связанных полей модели.
так что это мой пример тест:
class UnitaImmobiliareModelTest(TestCase):
def setUp(self):
self.user = User.objects.create_user(username='UtenteTest', password='testing')
self.studio = Studio.objects.create(
nome_studio="Studio Test",
utente_creatore_studio=self.user
)
self.commessa = Commesse.objects.create(
anno=timezone.now(),
nome_commesse="Commessa Test",
numero_commesse="0001",
descrizione="Descrizione della commessa",
somme_utilizzabili=10000,
tipo_committente=True,
utente_creatore=self.user,
studio_associato=self.studio,
utente_permesso=True
)
self.preventivoCommessaFase = PreventivoCommessaFase.objects.create(
codice="0001",
nome="test",
descrizione="testing",
commessa=self.commessa,
costi=2.00,
)
self.fasiPrestazionali = FasiPrestazionali.objects.create(
nome_fase="test001",
costo=3,
preventivi_commessa = self.preventivoCommessaFase
)

self.unitaImmobiliare1 = UnitaImmobiliare.objects.create(
codice="0002",
descrizione="test",
latitudine=2.2,
longitudine=1.2,
utente_creatore_unita=self.user,
preventivi_fase=self.preventivoCommessaFase
)
self.unitaImmobiliare2 = UnitaImmobiliare.objects.create(
codice="0003",
descrizione="test",
latitudine=2.2,
longitudine=1.2,
utente_creatore_unita=self.user,
preventivi_fase=self.preventivoCommessaFase
)

def test_calcola_spesa_totale(self):
expected_spesa_totale = Decimal('4.00')
result = calcola_spesa_totale(self.preventivoCommessaFase)
self.assertEqual(result, expected_spesa_totale)

Я пытаюсь протестировать функцию «calcola_spesa_totale»:
print(f"QuerySetData: {computi}")
print(computi[1].preventivi_fase.costi)
totali_unita_immobiliari = (
computi.values("descrizione")
.annotate(totale_costo=Sum(Cast("preventivi_fase__costi", FloatField())))
.order_by("descrizione")
)

print(f"somma totale: {totali_unita_immobiliari}")#asd

spesa_totale = sum(
Decimal(item["totale_costo"] or 0) for item in totali_unita_immobiliari
)
print(f"Spesa Totale Calcolata: {spesa_totale}") #asd
return spesa_totale`

`
проблема в том, что к тому времени, когда я вхожу в эту функцию, ошибка уже произошла, что означает, что
значение Preventivi_fase.costi уже установлено на 0.0
по моим исследованиям, это происходит внутри модели PreventivoCommessaFase def totale_fasi
это другая модель FasiPrestazionali, содержащая fk:
class FasiPrestazionali(models.Model):
nome_fase = models.CharField(max_length=150)
descrizione = models.TextField(null=True, blank=True)
data_termine = models.DateField(null=True, blank=True)
giorni_preavviso = models.IntegerField(blank=True, null=True)
pratica_boolean = models.BooleanField(default=False, null=True)
documenti = models.FileField(null=True, blank=True, upload_to="app/fasi_documenti/")
foto = models.ImageField(null=True, blank=True, upload_to="app/fasi_foto/")
costo = models.FloatField(null=True, blank=True)
preventivi_commessa = models.ForeignKey(
"PreventivoCommessaFase",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="preventivi_commessa_fase",
)
completata = models.BooleanField(
default=False
) # Nuovo campo booleano 'completata' con valore di default False
unita_immobiliare_fase = models.ForeignKey(
"UnitaImmobiliare",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="unita_immobiliare_fase",
)

ordine = models.IntegerField(default=0) # Nuovo campo per l'ordine

def __str__(self):
return self.nome_fase

**Я пытался создать preventivoCommessaFase после fasiPrestazionali или назначить fk перед созданием связанного метода. и, честно говоря, я также пробовал много чего другого, но больше даже не помню
пожалуйста, помогите, это сводит меня с ума. SOS
Я предполагаю, что проблема в этом: totale_fasi**
class PreventivoCommessaFase(models.Model):
codice = models.CharField(max_length=50, unique=True)
nome = models.CharField(max_length=150, null=True, blank=True)
descrizione = models.TextField(null=True, blank=True)
commitente_persona = models.ManyToManyField(
"CommitentePersona",
related_name="commitente_persona_preventivo_fase",
null=True,
blank=True,
)
commitente_giuridico = models.ManyToManyField(
"CommitenteGiuridico",
related_name="commitente_giuridico_preventivo_fase",
null=True,
blank=True,class PreventivoCommessaFase(models.Model):
codice = models.CharField(max_length=50, unique=True)
nome = models.CharField(max_length=150, null=True, blank=True)
descrizione = models.TextField(null=True, blank=True)
commitente_persona = models.ManyToManyField(
"CommitentePersona",
related_name="commitente_persona_preventivo_fase",
null=True,
blank=True,
)
commitente_giuridico = models.ManyToManyField(
"CommitenteGiuridico",
related_name="commitente_giuridico_preventivo_fase",
null=True,
blank=True,
)
committente_generico = models.ManyToManyField(
"CommittenteGenerico",
related_name="committente_generico_preventivo_fase",
null=True,
blank=True,
)
costi = models.FloatField(null=True, blank=True)
data_creazione = models.DateField(null=True, blank=True)
data_scadenza = models.DateField(null=True, blank=True)
diritti = models.BooleanField(default=False)
commessa = models.ForeignKey(
"Commesse",
related_name="commesse_preventivi_fase",
on_delete=models.SET_NULL,
null=True,
blank=True,
)

def __str__(self):
return self.codice

@property
def totale_fasi(self):
print(self)
totale = FasiPrestazionali.objects.filter(preventivi_commessa=self).aggregate(
Sum("costo")
)["costo__sum"]
print("terrazzo",totale)
return totale if totale else 0

def save(self, *args, **kwargs):
self.costi = self.totale_fasi
super().save(*args, **kwargs)

)
committente_generico = models.ManyToManyField(
"CommittenteGenerico",
related_name="committente_generico_preventivo_fase",
null=True,
blank=True,
)
costi = models.FloatField(null=True, blank=True)
data_creazione = models.DateField(null=True, blank=True)
data_scadenza = models.DateField(null=True, blank=True)
diritti = models.BooleanField(default=False)
commessa = models.ForeignKey(
"Commesse",
related_name="commesse_preventivi_fase",
on_delete=models.SET_NULL,
null=True,
blank=True,
)

def __str__(self):
return self.codice

@property
def totale_fasi(self):
print(self)
totale = FasiPrestazionali.objects.filter(preventivi_commessa=self).aggregate(
Sum("costo")
)["costo__sum"]
print("terrazzo",totale)
return totale if totale else 0

def save(self, *args, **kwargs):
self.costi = self.totale_fasi
super().save(*args, **kwargs)


Подробнее здесь: https://stackoverflow.com/questions/786 ... ed-model-f

Вернуться в «Python»