Answer the question
In order to leave comments, you need to log in
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=...
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)
print vegetable.tomato, vegetable.potatoes, vegetable.eggplant
.... "Tomato-delicious", none, none
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question