Reputation: 75
I am building menu items for Irvine
class and want to categorize them by Category
models.py
class Irvine(models.Model):
objects = None
name = models.CharField(max_length=50, verbose_name='Irvine Item')
description = models.TextField(null=True, blank=True)
size = models.FloatField(null=True, blank=True)
price = models.FloatField(null=True, blank=True)
published = models.DateTimeField(auto_now_add=True, db_index=True)
category = models.ForeignKey('Category', null=True, on_delete=models.PROTECT, verbose_name='Category')
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Irvine'
verbose_name = 'Irvine Item'
ordering = ['-published']
class Category(models.Model):
objects = None
name = models.CharField(max_length=30, db_index=True, verbose_name="Category")
published = models.DateTimeField(auto_now_add=True, db_index=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = '* Categories'
verbose_name = 'Category'
ordering = ['name']
view.py
def irvine(request):
irvine = Irvine.objects.all()
context = {'irvine': irvine}
return render(request, 'cafe/irvine.html', context)
def by_category(request, category_id):
santaanna = SantaAnna.objects.filter(category=category_id)
costamesa = CostaMesa.objects.filter(category=category_id)
irvine = Irvine.objects.filter(category=category_id)
categories = Category.objects.all()
current_category = Category.objects.get(pk=category_id)
context = {'santaanna': santaanna, 'categories': categories, 'costamesa': costamesa, 'irvine': irvine, 'current_category': current_category}
return render(request, 'cafe/by_category.html', context)
urls.py
urlpatterns = [
path('add/', ItemsCreateView.as_view(), name='add'),
path('<int:category_id>/', by_category, name='by_category'),
path('', index, name='index'),
path('irvine', irvine),
with
{% for i in irvine %}
{}
<tr class="danger">
<th scope="row" width="20%">{{ i.name }}</th>
<td width="60%">{{ i.description }}</td>
<td width="10%">{{ i.size }}</td>
<td width="10%">{{ i.price }}</td>
</tr>
{% endfor %}
I can grab all items from class Irvine, but how do i get items from this class by category
Upvotes: 0
Views: 169
Reputation: 138
You can't directly check using i.category
because it has list of values.
Try using i.category.name
.
If you have serializer, please update the full code.
{% for i in irvine %} {% if i.category.name == 'Appetizers' %}
, it will work
Upvotes: 1