# faire des calcule entre des champs d'un modele

**URL:** <https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542>\
**Category:** Using the ORM\
**Created:** [March 10, 2022, 2:59pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542 "2022-03-10T14:59:59Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sirchemaya](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sirchemaya/32/7586_2.png) [@Sirchemaya](https://forum.djangoproject.com/u/Sirchemaya)\
**Post date:** [March 10, 2022, 2:59pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/1 "2022-03-10T14:59:59Z")

</div>

bonjour à tous,  
pouvez vous me donner un lien ou des astuce pour faire des calculs(addition et multiplication)entre deux champs dans un model

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 10, 2022, 3:14pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/2 "2022-03-10T15:14:57Z")

</div>

Response from Google Translate:

Il serait utile que vous soyez plus précis sur ce que vous essayez exactement d’atteindre.

Les champs d’un modèle sont des attributs d’une classe qui fonctionnent exactement comme tout autre attribut serait utilisé dans n’importe quelle classe Python standard.

Si vous pouviez fournir des détails sur le problème spécifique que vous rencontrez, nous pourrions être en mesure de fournir une réponse plus précise.

And the original English:

It would be helpful if you were more specific with what exactly you’re trying to achieve.

Fields in a model are attributes on a class that function exactly like how any other attribute would be used in any standard Python class.

If you could supply details about the specific problem you’re encountering, we might be able to provide a more specific response.

---

<div class="post-metadata">

**Author:** ![Sirchemaya](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sirchemaya/32/7586_2.png) [@Sirchemaya](https://forum.djangoproject.com/u/Sirchemaya)\
**Post date:** [March 10, 2022, 3:32pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/3 "2022-03-10T15:32:55Z")

</div>

j’ai trois champ un montant\_devise,devise et montant\_xaf, je souhaite que montat\_xaf = montant\*devise

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 10, 2022, 4:00pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/4 "2022-03-10T16:00:19Z")

</div>

From Google translate:

D’après ce que vous avez écrit :

> montat\_xaf = montant\*devise

C’est une syntaxe Python parfaitement valide. Donc, je suppose que vous voulez plus d’informations que cela.

Mais vous n’avez pas fourni assez de contexte.

“Je veux…” - Quand ? Où? Pourquoi? Pour en faire quoi ? Est-ce pour le rendu dans un modèle ? Passer à un autre calcul ?  
Quel est votre objectif ultime pour cela ?

Soyez précis et fournissez tous les détails pertinents sur ce que vous essayez d’accomplir.

And the original English:

From what you wrote:

> montat\_xaf = montant\*devise

That’s perfectly valid Python syntax. So, I’m assuming you want more information than that.

But you have not provided nearly enough context.

“I want …” - When? Where? Why? To do what with it? Is this for rendering in a template? To pass along to another calculation?  
What is your ultimate objective for this?

Be specific and provide all the relevant details about what you’re trying to achieve.

---

<div class="post-metadata">

**Author:** ![axeljacobs](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/axeljacobs/32/3939_2.png) [@axeljacobs](https://forum.djangoproject.com/u/axeljacobs)\
**Post date:** [March 11, 2022, 4:07pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/5 "2022-03-11T16:07:28Z")

</div>

Qu’est ce que vous voulez faire avec le résultat du calcul ? Afficher ? Stocker ?

Par example si vous avez un modèle

```auto
class MonModele(models.Model):
    x = models.IntegerField(....)
    y = models.IntegerField(....)

    def xy(self):
        retrun self.montant * self.devise

```

Dans votre code quand vous avez un instance d’un objet MonModele vous pouvez accéder à la méthode xy pour obtenir le résultat du calcul.

création d’une instance de l’object MonModele

```auto
prix = MonModele.objects.create(x=2, y=5)

```

Dans le code:

```auto
resultat = prix.xy()

```

Est-ce que ca vous aide ?

---

<div class="post-metadata">

**Author:** ![Sirchemaya](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sirchemaya/32/7586_2.png) [@Sirchemaya](https://forum.djangoproject.com/u/Sirchemaya)\
**Post date:** [March 14, 2022, 8:16am UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/6 "2022-03-14T08:16:27Z")

</div>

voici mon modele:  
je souhaite que mt\_xaf = mt\_devise\* devise

class Dossier(models.Model):

statut=((‘Valider en Agance’,‘Valider en Agance’),  
(‘Valider controle BEAC’,‘Valider controle BEAC’),  
(‘Rejeter Controleur BEAC’,‘Rejeter Controleur BEAC’)  
)

raison\_sociale=models.CharField(max\_length=50)  
motif=models.ForeignKey(Motif,null=True,on\_delete=models.SET\_NULL)  
devise=models.FloatField()  
mt\_devise=models.DecimalField(max\_digits=70, decimal\_places=2)  
mt\_xaf=models.PositiveIntegerField(default=1)  
situation\_cpt=models.CharField(max\_length=10)  
beneficiaire=models.CharField(max\_length=50)  
statut=models.CharField(max\_length=50,choices=statut,default=‘Valider en Agance’)  
create\_time=models.DateTimeField(auto\_now\_add=True)

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [March 14, 2022, 11:58am UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/7 "2022-03-14T11:58:31Z")

</div>

Il est vrai que l’objectif est flou … (attention au melange des types de champ FloatField, DecimalField et PositiveIntegerField…)

```auto
class Dossier(models.Model):
    # fields
    def save(self, *args, **kwargs):
        if self.mt_devise and self.devise:
            self.mt_xaf = self.mt_devise * self.devise
        super(Dossier, self).save(*args, **kwargs)

```

?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 14, 2022, 12:06pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/8 "2022-03-14T12:06:50Z")

</div>

From Google Translate:

Ce que vous ne voulez **pas** faire, c’est stocker le résultat d’un calcul comme celui-ci dans votre base de données - du moins pas dans la couche Django. C’est une **extrêmement** _mauvaise_ idée. (Cela enfreint les principes de la base de données consistant à maintenir l’intégrité et à fournir une source d’informations unique.) Plus précisément, dans ce cas, il existe plusieurs façons de mettre à jour l’un de ces champs sans passer par la méthode `save` - ce qui signifie désormais votre modèle est incorrect.

Lorsque vous avez une valeur dérivée d’autres champs dans votre modèle, vous souhaitez effectuer ce calcul lorsqu’il est nécessaire de l’utiliser, pas seulement pour les stocker.

* * *

And the original English:

What you do **not** want to do is store the result of a calculation like that in your database - at least not in the Django layer. This is an **extremely** _bad_ idea. (It violates the database principles of maintaining integrity and providing a single source of information.) Specifically in this case, there are multiple ways in which one of those fields can be updated that do not go through the `save` method - which now means your model is incorrect.

When you have a value derived from other fields in your model, you want to perform that calculation when it is needed to be used, not just to store them.

---

<div class="post-metadata">

**Author:** ![Sirchemaya](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sirchemaya/32/7586_2.png) [@Sirchemaya](https://forum.djangoproject.com/u/Sirchemaya)\
**Post date:** [March 14, 2022, 12:35pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/9 "2022-03-14T12:35:38Z")

</div>

ok, merci pour votre apport, mon besoin, c’est de pouvoir afficher le résultat dans une page html

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 14, 2022, 12:46pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/10 "2022-03-14T12:46:51Z")

</div>

Ma recommandation générale serait de créer une [méthode de modèle](https://docs.djangoproject.com/fr/4.0/topics/db/models/#model-methods-1) pour ce champ. Cela ressemblerait à quelque chose comme:

```auto
def mt_xaf(self):
    return self.mt_devise * self.devise

```

Vous pourrez alors référencer mt\_xaf dans votre modèle comme n’importe quel autre champ.

* * *

And the original English:

My general recommendation would be to create a [model method](https://docs.djangoproject.com/en/4.0/topics/db/models/#model-methods-1) for that field. It would look something like:

```auto
def mt_xaf(self):
    return self.mt_devise * self.devise

```

You would then be able to reference mt\_xaf in your template like any other field.

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [March 14, 2022, 12:51pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/11 "2022-03-14T12:51:53Z")

</div>

… and wrap that using `@property`?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 14, 2022, 1:20pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/12 "2022-03-14T13:20:37Z")

</div>

You can if you want. I never bother - I don’t see the value when the only usage is going to be a template reference.  
Even if it’s being used elsewhere, I prefer it being explicitly obvious that this attribute is a derived value and not an intrinsic value.

---

<div class="post-metadata">

**Author:** ![Sirchemaya](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/sirchemaya/32/7586_2.png) [@Sirchemaya](https://forum.djangoproject.com/u/Sirchemaya)\
**Post date:** [March 14, 2022, 1:22pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/13 "2022-03-14T13:22:02Z")

</div>

> [@KenWhitesell](#):
>
> ` mt_xaf`

Merci beaucoup, j’ai pu avoir le résultat attendu

---

<div class="post-metadata">

**Author:** ![yankeebrain](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/yankeebrain/32/17812_2.png) [@yankeebrain](https://forum.djangoproject.com/u/yankeebrain)\
**Post date:** [December 15, 2023, 11:27pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/14 "2023-12-15T23:27:29Z")

</div>

bonjour merci de m’aider svp

Class Puissance(models.Model):  
p1 = models.IntegerField(default=0)  
p2 = models.IntegerField(default=0)  
p3 = models.IntegerField(default=0)  
p4 = models.IntegerField(default=0)

comment faire pour calculre le max de ces champs?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 15, 2023, 11:48pm UTC](https://forum.djangoproject.com/t/faire-des-calcule-entre-des-champs-dun-modele/12542/15 "2023-12-15T23:48:53Z")

</div>

@yankeebrain - Please open a new topic to discuss your issue. Also, you’ll need to be more specific about what you’re looking for. Do you want to know which field has the largest value in each instance? Or are you looking to find which instance has the largest value for each field? Or are you looking for the largest value among all instances across all fields?
