B
B
blackbb2022-03-29 22:16:39
Django
blackbb, 2022-03-29 22:16:39

How to calculate the average price per room through aggregate?

There are three models

class Hotel(models.Model):
    user = models.ForeignKey(MyUser, on_delete=models.CASCADE, verbose_name='Владелец')
    title = models.CharField(max_length=100, verbose_name='Название')

    def average_price(self):
        return self.number_set.aggregate(Avg('get_price'))

class Number(models.Model):
    hotel = models.ForeignKey(Hotel, default=1, on_delete=models.CASCADE, verbose_name='Отель')
    title = models.CharField(max_length=100, verbose_name='Название')

    def get_price(self):
        return self.numberprice_set.all.aggregate(Avg('price'))

class NumberPrice(models.Model):
    start = models.DateField(verbose_name='Начало периода')
    finish = models.DateField(verbose_name='Конец периода')
    price = models.IntegerField(null=True, blank=True, verbose_name='Цена')
    number = models.ForeignKey(Number, on_delete=models.CASCADE, verbose_name='Номер')

Hotels are displayed in the template, you need to display the average price of rooms in each hotel. I wrote methods in models, but I don’t know how to call the get_price method from the average_price method of the Hotel model. I did not make the price a field in the number model, since the price will depend on the periods (dates).

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question