Home > Mobile >  How to return child object names along with parent details in django
How to return child object names along with parent details in django

Time:01-10

I have two models Destination and Cruise

#Models
class Destination(models.Model):
    name = models.CharField(unique= True, null= False, blank=False, max_length= 50)
    description = models.TextField(max_length= 2000, null= False, blank=False)
    slug = models.SlugField()

    def __str__(self) -> str:
          return self.name

class Cruise(models.Model):
    name = models.CharField(unique= True, null= False, blank=False, max_length= 50)
    description = models.TextField(max_length= 2000, null= False, blank=False)
    destinations = models.ForeignKey("Destination", null=True, blank=True, on_delete=models.SET_NULL)

Im trying to show the Destination details along with all the Cruises under that destination.

#Views
class DestinationDetailView(DetailView):
    template_name = 'destination_detail.html'
    queryset = models.Destination.objects.all()
       
    context_object_name = "destination"

HTML

#html
{% block content %}

Destination Name = {{destination.name}}
Description = {{destination.description}}
Cruise = {{destination.cruises}}

{% blockend content %}

Please advise how to print all cruises under perticual destination.

CodePudding user response:

I expect you want to display the contents of some cruise fields in you html.

You can use the for template tag as described here, e.g.:

#html
{% block content %}

Destination Name = {{destination.name}}
Description = {{destination.description}}
Cruise = 
{% for cruise in destination.cruise_set.all %}
{{ cruise.name }} </br>
{% endfor %}

{% blockend content %}

CodePudding user response:

This solved my problem by adding for loop in HTML.

#html

{% block content %}

Destination Name = {{destination.name}}
Description = {{destination.description}}
Cruise = 
{% for cruise in destination.cruises.all %}
{{ cruise.name }} </br>
{% endfor %}

{% blockend content %}
  •  Tags:  
  • Related