newprogrammer12
newprogrammer12

Reputation: 243

Query in Django template

I am trying to query inside a django template, but i am just not sure how to correctly phrase the query, i have two models 1-category 2-items and i am trying to get all the items of a specific category from it's ID {% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}

here is the complete template:

<div class="inventory-content">
    <div class='category'>
        <div>Categories</div>
        <div class='category-checkbox'>
            {%for category in items%}
            <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}">
            <label for="{{category.name}}"> {{category.name}}</label><br>
            {%endfor%}
        </div>
    </div>
    <div class='items'></div>
    
</div>    

<script>
    $('.category-checkbox input[type="checkbox"]').on('click', function() {
        if ($(this).is(':checked')) {
          // Add the element to the div with an id identifier
          $('.items').append(`<div id="item_${this.id}">{% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}</div>`);
        } else {
          // Remove the element from the div targeted by the id identifier
          $(`#item_${this.id}`).remove();
        }
      });
</script>

models.py:

class Category(models.Model):
    name = models.CharField(max_length=150)
    vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE,related_name='category')
    def __str__(self):
        return self.name
class Item(models.Model):
    name = models.CharField(max_length=255)
    part_number = models.IntegerField(blank=True)
    ROB = models.IntegerField(default=0)
    category=models.ForeignKey(Category,related_name='items',on_delete=models.CASCADE)

    def __str__(self):
        return self.name

views.py:

def index(request,pk):
    vessel_id = Vessel.objects.get(id=pk)
    categories = vessel_id.category.all()
    category = Category.objects.all()
    item = categories.prefetch_related(
        'items')
    context ={"vessel_id":vessel_id,'items':item,"category":category}
    return render(request,'inventory.html',context)

   

also i have been told it's bad practice to write query inside the template, so if you can guide me what better way could i have achieved this ?which is querying for all items in a specific category when checked

Upvotes: 0

Views: 663

Answers (2)

NixonSparrow
NixonSparrow

Reputation: 6388

As vessel_id you have Vessel object, not its id. Be careful with that. You should definitely get what you need in your views. You already know, how to pass and use context. Even for scripts, but it might be little more tricky. You can try:

script_insider = ''.join([item.name for item in Category.objects.get(id=id_you_want).items.all()])

It should sum your Items names to that: 'name_1name_2name_3'. You can use ' ' instead of '', then whitespace will separate the names: 'name_1 name_2 name_3'.

In templates you cannot use freely the code. You will mostly use for loops and if conditionings. You can also read about Custom Tags that can sometimes be more precise with template values.

Upvotes: 1

sudden_appearance
sudden_appearance

Reputation: 2195

You are not able to call methods with arguments in Django templates, so there is no way you can write a query inside template.

The only right way is to query inside a view and then pass the ResultSet to context inside render() function.

Upvotes: 1

Related Questions