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,381
  • 4
  • 16
  • 39
  • You can send your `home_team_chr` and `home_team_chr` as **serialized** objects and then iterate over the fields and check for the True values in booleans. – Pedram Dec 07 '19 at 07:38
  • I'm sorry, I don't know about serializations. Can you suggest a source that i can investigate? – Yusuf Numan YILMAZ Dec 07 '19 at 07:48
  • Check out [this](https://stackoverflow.com/a/2311015/9733868). – Pedram Dec 07 '19 at 07:58
  • Glad to help :) I also added an answer as SO suggests not to answer the question in the comments. Please consider accepting that as well. – Pedram Dec 07 '19 at 08:25

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
  • 3,485
  • 3
  • 17
  • 32