Home > Enterprise >  Django : Only display model items that match with for each category and have at least one item
Django : Only display model items that match with for each category and have at least one item

Time:01-04

Here are the models I've created

class Jeu(models.Model):
    nom = models.CharField('Nom du jeu', max_length=100)
    logo = models.ImageField(blank=True)

    def courses_a_venir():
        return self.course_set.filter(date_evenement__gte = datetime.today()).order_by('date_evenement')

    def courses_passees():
        return self.course_set.filter(date_evenement__lt = datetime.today()).order_by('-date_evenement')[:3]

class Course(models.Model):
    jeu = models.ForeignKey(Jeu, verbose_name='Nom du jeu', on_delete=models.CASCADE)
    ligue = models.ForeignKey(Ligue, on_delete=models.CASCADE)
    circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE)
    date_evenement = models.DateTimeField("Date de la course")

Here is the view :

def home(request):
    jeux = Jeu.objects.all()
    return render(
        request,
        'base_site/home.html',
        context={'title': 'Accueil',  'jeux': jeux,}
    )

And then here is the HTML code :

{% for jeu in jeux %}
<h3>{{ jeu.nom }}</h3><br>
<div >
  {% for course in jeu.courses_a_venir %}
  <div >
    <div >
      <!--<img src="..."  alt="...">-->
      <div >
        <h5 >{{ course.date_evenement }}</h5>
        <p >This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      </div>
      <div >
        <small >{{ course.date_evenement }}</small>
      </div>
    </div>
  </div>
  {% endfor %}
</div><br>
{% endfor %}
<br><br>

The thing is, one "Jeu" can be called by multiple "Course". As it is currently implemented in the HTML code, it retrieves all the "Jeu" in the table "Jeu" and the "Course" associated, no matter if some "Jeu" don't contain any "Course".

Does somebody know how to display only the "Jeu" that contain at least one "Course" ?

CodePudding user response:

You can access all the courses a jeux is linked to by using course_set. This is true for all your models, you can perform a reverse lookup using {model}_set or by specifying a related_name on the ForeignKey.

You can find an example here: https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_one/

course_set is a queryset so you can using the all, filter,... operations on them as normal.

jeux = Jeu.objects.all()
for jeu in jeux:
    if jeu.course_set.exists():
        # jeu has a course
    else:
        # jeu does not have a course
  • Related