Home > Enterprise >  Django : HTML render from multiple tables linked many-to-one relations
Django : HTML render from multiple tables linked many-to-one relations

Time:01-04

I have multiple models which are defined like that :

class Circuit(models.Model):
    nom = models.CharField(max_length=120)
    pays = models.CharField(max_length=120, choices=pays_choices)
    image = models.ImageField(blank=True)

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

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

The Circuit and Jeu models are independent and are respectively gathering data of race tracks and racing games. The Course model is gathering all the races that will happen, and it is taking data from the Circuit and Jeu tables.

In the HTML part, I want to display cards of the races that are coming, like that :

enter image description here

The picture on top should come from the image of the circuit, in the Circuit model. The date and circuit are coming from the Course table.

To achieve that, I already added in the Jeu model a reverse lookup to only take the races of each game :

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

    def courses(self):
         return self.course_set.all().order_by('date_evenement')

But how do I get now the image of the circuit, from the Circuit model ?

CodePudding user response:

I would send the queryset of Course to the html and render all the information like this:

#view 
def some_view(request, jou_id):
    queryset = Jou.objects.get(pk=jou_id).courses()
    return render(request, 'template.html', context={'courses':queryset})

# template
{% for course in courses %}
<img src="{{course.circuit.image.url}}">
{{ course.date_evenement }}
{% endfor %}

# url
path('somepath/<int:jou_id>', views.some_view, name='index'),

More information can be found in the documentation.

  • Related