简体   繁体   中英

how to if condition on Foreign Key in Django

this is my model

class MainCategories(models.Model):
    name = models.CharField(null=True,blank=True,max_length=150)

    def __str__(self):
        return u'{0}'.format(self.name)


class SubCategories(models.Model):
    main_category = models.ForeignKey(MainCategories,null=True,blank=True,related_name = 'MainCategories', on_delete=models.CASCADE)
    name = models.CharField(null=True,blank=True,max_length=150)
    
    def __str__(self):
        return u'{0}'.format(self.name)

this my view.py

def home(request):

    sub_category = SubCategories.objects.all()
    print('subbbb', sub_category)

    c = {
        'sub_category' : sub_category
    }

    return render(request,'core/home.html', c)

this is my base.html

<li>
<a href="javascript:;">Process Equipment & Project Division<i class="fa fa-angle-right"></i></a>
  <ul class="sub-menu left">
   {% if sub_category.Main_category.Name ==  "Process Equipment & Project Division" %}
     {% for sub in sub_category%}
      <li><a href="header-style-1.html">{{sub.name}}</a></li>
      {%endfor%}
      {%endif%}
      </ul>
     </li>

iam created if condition in "li" tag. but its not working. the if condition is not properly..

How I undestand sub_category is QueryDict. You connot use it "sub_category.Main_category", you must use so 'sub.main_category' to if condition after for loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM