简体   繁体   中英

Multiply two fields together in django database

I am new to Django and i have been trying to do this for sometime now.

models.py

class Majitele(models.Model):
    cena_p = models.DecimalField(decimal_places=2, max_digits=10, null=True)
    cena_l = models.DecimalField(decimal_places=2, max_digits=10, null=True)
    lv = models.IntegerField(null=True)
    katastr = models.CharField(max_length=40, null=True)
    jmeno = models.CharField(max_length=40, null=True)
    ulice = models.CharField(max_length=30, null=True)
    mesto = models.CharField(max_length=30, null=True)
    psc = models.IntegerField(null=True)
    v_pole = models.DecimalField(decimal_places=4, max_digits=10, null=True)
    v_les =  models.DecimalField(decimal_places=4, max_digits=10, null=True)
    v_celkem = models.DecimalField(decimal_places=4, max_digits=10, null=True)
    cena_pole = models.DecimalField(decimal_places=4, max_digits=10, null=True)
    cena_les = models.DecimalField(decimal_places=4, max_digits=10, null=True)
    cena_rok = models.DecimalField(decimal_places=4, max_digits=10, null=True)
    nevyplaceno = models.IntegerField(null=True)
    podil = models.CharField(max_length=5, null=True)
    hlasu = models.IntegerField(null=True)
    poznamka = models.CharField(max_length=200, null=True)
    prezence = models.BooleanField(null=True)
    vyplatni = models.BooleanField(null=True)
    postou = models.BooleanField(null=True)
    osobne = models.BooleanField(null=True)

    def __str__(self):
        return '%s'%(self.jmeno)

Here is what would i like to do: Take v_pole value then cena_p value and multiply them together and the result should then be saved in the cena_pole field.

I tried this:

Majitele.objects.all().annotate(vypocet_c=F('cena_p') * F('v_pole')).update(cena_pole=vypocet_c)

Is there even a way how to do it? Thanks for any advice.

Yes, you can update this with:

from django.db.models import F

Majitele.objects.all().update()

That being said, if cena_pole is always the multiplication of cena_p and v_pole , then it might be better to remove this field, and use annotations (for example in a manager), to filter, calculate, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM