django - how to bind records of table with calculated count values from another table

annlii

In my application I have a list of trainings. One field on this list should display number of booking for each of training. To show what I mean I prepared SQL query:

SELECT *
FROM club_training a
LEFT JOIN
(SELECT training_id, count(*)
FROM club_booking
group by training_id) b
ON a.id = b.training_id

Could you give me some advice how to do it in django? I used Booking.objects.all().values('training_id').annotate(booked_amount=Count('training_id')) in my code, but the result is that all count values for all trainings are displayed for each training on the list. Should be displayed one count value which is apropriate for each training.

enter image description here

views.py

class HomePageView(TemplateView):
    """Home Page with list of trainings"""
    template_name = 'club/training_list.html'


    def get_context_data(self, **kwargs):
        now = datetime.datetime.now()
        context = super(HomePageView, self).get_context_data(**kwargs)
        context['trainings'] = Training.objects.filter(state="A", training_date__gte=now).order_by('training_date', 'start_time')
        for each_training in context['trainings']:       
            each_training.diff = each_training.availability - each_training.counter
            each_training.counter = Booking.objects.all().values('training_id').annotate(booked_amount=Count('training_id'))
        return context 

models.py

class Training(models.Model):
    """Class for plan training"""
    STATE = (
        ('A', 'Active'),
        ('I', 'Inactive'),
    )
    name = models.ForeignKey('TrnDesc')
    instructor = models.ForeignKey('Instructor')
    start_time = models.TimeField(blank=True)
    end_time = models.TimeField(default='00:00:00')
    availability = models.PositiveIntegerField(default=15)
    state = models.CharField(max_length=1, choices=STATE, default='A')
    training_date = models.DateField(default=date.today)
    counter = models.PositiveIntegerField(default=0)
    def __str__(self):
        return self.name.name

class Booking(models.Model):
    """Data of people which book fitness classes"""
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    phone = models.CharField(max_length=10)
    training = models.ForeignKey('Training')
    def __str__(self):
        return self.training.name.name

training_list.html

{% extends 'club/base.html' %}

{% block content %}

        <ul class="nav nav-pills">
            <li role="presentation" class="active"><a href="#">Fitness Classes</a></li>
            <li role="presentation"><a href="#">Join Us</a></li>
            <li role="presentation"><a href="#">Contact Us</a></li>
        </ul>
        <br></br>
    {% regroup trainings by training_date as date_list %}
    {% for date in date_list %}
        <div class="panel panel-default">


            <div class="panel-heading">{{date.grouper|date:"l, d F o"}}</div>


            <table class="table">
                <tr>
                    <th style="width: 20%">Training name</th>
                    <th style="width: 30%">Training description</th>
                    <th style="width: 10%">Instructor</th>
                    <th style="width: 10%">Start time</th>
                    <th style="width: 10%">End time</th>
                    <th style="width: 10%">Left</th>
                    <th style="width: 10%">Test_counter</th>
                    <th style="width: 10%">Actions</th>
                </tr>


                {% for training in date.list %}

                <tr>
                    <td>{{training.name}}</td>
                    <td>{{training.name.desc}}</td>
                    <td>{{training.instructor}}</td>
                    <td>{{training.start_time|time:"H:i"}}</td>
                    <td>{{training.end_time|time:"H:i"}}</td>
                    <td>{{training.diff}}</td>
                    <td>{{training.counter}}</td>
                    <td><a href="{% url 'book' training_id=training.pk%}"><button type="button" class="btn btn-primary">Book</button></a></td>
                </tr>

                {% endfor %}    
            </table>
        </div>
    {% endfor %}

{% endblock %}
LostInThought
 for each_training in context['trainings']:       
        each_training.diff = each_training.availability - each_training.counter
        each_training.counter = Booking.objects.filter(training_id=each_training.id).count()  # just modify this line
    return context 

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Selecting records from a table and then selecting a count of records from another table

From Dev

selecting records from main table and count of each row in another table

From Dev

Retrieving records from one table based in 'similar' values of another table

From Dev

How to update the records from another table

From Dev

How to fetch records from another table in a query?

From Dev

How to count rows from another table to affect another table

From Dev

How to insert into a table new records based on info from another table?

From Dev

How to select records from a table when a condition of another table is satisfied

From Dev

django: how to make an attribute of a table be count of entries in another table

From Dev

How use count for value from another table

From Dev

How to count data from another table

From Dev

MySQL select Distinct records in 1 table and count each group based on values in another table

From Dev

How to Get VALUES from another table into another table in PHP/MySQL

From Dev

Updating records in table with ID from another table

From Dev

Selecting records from a table not in another table

From Dev

get records without records from another table

From Dev

How to select all records from one table that do not exist in another table for certain condition in another table?

From Dev

How to insert values from another table in PostgreSQL?

From Dev

How to get referenced values from another table?

From Dev

How to copy values from table for another column

From Dev

How to echo values from another table?

From Dev

Find total count and average based of values from another table

From Dev

Find total count based of values from another table

From Dev

How to combine records from different table into one record set with count

From Dev

How to update table records with another table

From Dev

How can i write sql code to bring values from another table and use count function?

From Dev

how to get the count of records in one table based on two date fields in another table

From Dev

Count Row from another table

From Dev

Filter by count from another table

Related Related

  1. 1

    Selecting records from a table and then selecting a count of records from another table

  2. 2

    selecting records from main table and count of each row in another table

  3. 3

    Retrieving records from one table based in 'similar' values of another table

  4. 4

    How to update the records from another table

  5. 5

    How to fetch records from another table in a query?

  6. 6

    How to count rows from another table to affect another table

  7. 7

    How to insert into a table new records based on info from another table?

  8. 8

    How to select records from a table when a condition of another table is satisfied

  9. 9

    django: how to make an attribute of a table be count of entries in another table

  10. 10

    How use count for value from another table

  11. 11

    How to count data from another table

  12. 12

    MySQL select Distinct records in 1 table and count each group based on values in another table

  13. 13

    How to Get VALUES from another table into another table in PHP/MySQL

  14. 14

    Updating records in table with ID from another table

  15. 15

    Selecting records from a table not in another table

  16. 16

    get records without records from another table

  17. 17

    How to select all records from one table that do not exist in another table for certain condition in another table?

  18. 18

    How to insert values from another table in PostgreSQL?

  19. 19

    How to get referenced values from another table?

  20. 20

    How to copy values from table for another column

  21. 21

    How to echo values from another table?

  22. 22

    Find total count and average based of values from another table

  23. 23

    Find total count based of values from another table

  24. 24

    How to combine records from different table into one record set with count

  25. 25

    How to update table records with another table

  26. 26

    How can i write sql code to bring values from another table and use count function?

  27. 27

    how to get the count of records in one table based on two date fields in another table

  28. 28

    Count Row from another table

  29. 29

    Filter by count from another table

HotTag

Archive