Search code examples
djangodatabasedjango-queryset

How to fetch data with the given order from the database ? (django)


I have a model in which there are different fields of data, and a field of "section-order" is given. now i want to fetch that data into the bootstrap accordians with respect to the "section-order". for example the section-order = 1 should come in first accordion and likewise

**MODELS **

class casestudy_list(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=255)


    def __str__(self):
        return self.title

class CaseStudyContent(models.Model):
    id = models.AutoField(primary_key=True)
    case_study = models.ForeignKey(casestudy_list, on_delete=models.CASCADE)
    section_order = models.IntegerField()
    section_title = models.CharField(max_length=255)

    content_text = models.TextField(blank=True)
    content_img = models.ImageField(upload_to='casestudy/images', default="")



   def __str__(self):
       return self.section_title

VIEWS

def home(request):
    casestudy_obj = casestudy_list.objects.all().values()
    template = loader.get_template('home.html')
    context = {
    'casestudy_obj' : casestudy_obj, #making the object for accessing purposes
    }
    return HttpResponse(template.render(context, request))

def casestudy(request, id):
    casestudy_obj = casestudy_list.objects.get(id=id)
    template = loader.get_template('casestudy.html')
    context = {
    'casestudy_obj' : casestudy_obj, #making the object for accessing purposes
   
    }
    return HttpResponse(template.render(context, request))

on the home page, once the user clicks on any link it reidrects to the casestudy page.


Solution

  • Use the render function to make the code a bit more concise. Sort your queryset according to section_order with the order_by() method.

    from django.shortcuts import render, get_object_or_404
    
    def casestudy(request, id):
        # results in 404 error when no object is found with given id
        casestudy_obj = get_object_or_404(casestudy_list, id=id)
        casestudy_content = CaseStudyContent.objects.filter(case_study=casestudy_obj).order_by('section_order')
        context = {
            'casestudy_obj': casestudy_obj,
            'casestudy_content': casestudy_content,
        }
        return render(request, 'casestudy.html', context)
    

    Then, with those two variables passed to the casestudy.html template you can insert it via curly braces.

    <div class="accordion" id="accordionExample">
      {% for content in casestudy_content %}
        <div class="card">
            <div class="card-header" id="heading{{ content.id }}">
                <h2 class="mb-0">
                    <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse{{ content.id }}" aria-expanded="true" aria-controls="collapse{{ content.id }}">
                        {{ content.section_title }}
                    </button>
                </h2>
            </div>
            <div id="collapse{{ content.id }}" class="collapse {% if forloop.first %}show{% endif %}" aria-labelledby="heading{{ content.id }}" data-parent="#accordionExample">
                <div class="card-body">
                    <p>{{ content.content_text }}</p>
                    {% if content.content_img %}
                    <img src="{{ content.content_img.url }}" class="img-fluid" alt="{{ content.section_title }}">
                    {% endif %}
                </div>
            </div>
        </div>
      {% endfor %}
    </div>
    

    You did not show your template. I hope above example for an accordion helps.