L
L
lehubozedo2017-08-24 15:24:57
Django
lehubozedo, 2017-08-24 15:24:57

How to pull out the total price from this “self.gifts.all()” with one request?

There are three models, each has a price field

class Tomato(models.Model):
    price=...
class Potatoes(models.Model):
    price=...
class Eggplant(models.Model):
    price=...

And there is a 4th model:
class Vegetable(models.Model):
    tomato = models.OneToOneField(Tomato, verbose_name='Томат', on_delete=models.CASCADE, blank=True, null=True)
    potatoes = models.OneToOneField(Potatoes, verbose_name='Potatoes', on_delete=models.CASCADE, blank=True, null=True)
    eggplant = models.OneToOneField(Eggplant, verbose_name='Eggplant', on_delete=models.CASCADE, blank=True, null=True)
    gifts = models.ManyToManyField('self', blank=True, symmetrical=False)

How to get the total price from this (self is Vegetable) "self.gifts.all()" with one query?
The problem is that ANY instance of vegetable should and only contains one thing:
print vegetable.tomato, vegetable.potatoes, vegetable.eggplant
.... "Tomato-delicious", none, none

gifts of course, contains links to several instances of Vegetable, how to get the sum of the price of these instances?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Sergeev, 2017-08-24
@SergeevAI

That's how you can. Just google for select and prefetch_related for self.gifts.all()

class Vegetable(models.Model):
    tomato = models.OneToOneField(Tomato, verbose_name='Томат', on_delete=models.CASCADE, blank=True, null=True)
    potatoes = models.OneToOneField(Potato, verbose_name='Potatoes', on_delete=models.CASCADE, blank=True, null=True)
    eggplant = models.OneToOneField(Eggplant, verbose_name='Eggplant', on_delete=models.CASCADE, blank=True, null=True)
    gifts = models.ManyToManyField('self', blank=True, symmetrical=False)

    @property
    def get_price(self):
        tomato = self.tomato.price if self.tomato is not None else 0
        potatoes = self.potatoes.price if self.potatoes is not None else 0
        eggplant = self.eggplant.price if self.eggplant is not None else 0
        return sum([tomato, potatoes, eggplant])
        
    @property   
    def get_gift_price(self):
        return sum([x.get_price for x in self.gifts.all()])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question