0

I created a model object. This object has several boolean fields.

# models.py

class TeamCharacteristic(models.Model):
     team = models.ForeignKey('Teams',on_delete=models.CASCADE)
     power1 = models.BooleanField(null=True, blank=True)
     power2 = models.BooleanField(null=True, blank=True)
     power3 = models.BooleanField(null=True, blank=True)
     power4 = models.BooleanField(null=True, blank=True)
     power5 = models.BooleanField(null=True, blank=True)

class Meta:
     verbose_name = 'Team style'
     verbose_name_plural = 'Teams style'

def __str__(self):
     return "{} 's style".format(
         self.team,
     )

Some of them are right and others are wrong. I want to show only the fields that have the correct value in the template. How can I do this in a shorter way instead of checking each field individually?

# views.py
from django.shortcuts import render, get_object_or_404
from .models import Matches
from denemee.apps.home.models import TeamCharacteristic


def matches_details(request, page_id=None, team=None, **kwargs):
    m_detail = get_object_or_404(Matches, id=page_id)
    home_team_chr = get_object_or_404(TeamCharacteristic, team=m_detail.h_team)
    away_team_chr = get_object_or_404(TeamCharacteristic, team=m_detail.a_team)
    payload = {
        'm_detail': m_detail,
        'home_team_chr': home_team_chr,
        'away_team_chr': away_team_chr
    }
    return render(request, 'match_detail.html', payload)
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43

1 Answers1

1

You can send your home_team_chr and home_team_chras serialized objects and then iterate over the fields and check for the True values in booleans.

Check out this answer for more details.

Pedram Parsian
  • 3,750
  • 3
  • 19
  • 34