I'm trying to a write a search function for table reserving from a restaurant, I have a restaurant model:
class Restaurant(models.Model):
"""
Table Restaurant
=======================
This table represents a restaurant with all necessary information.
"""
name = models.CharField(max_length=70)
caterer = models.ForeignKey(Caterer, on_delete=models.CASCADE, null=True)
address = models.OneToOneField(Address, on_delete=models.CASCADE, null=True)
kitchen_type = models.IntegerField(choices=KITCHEN_TYPE, null=True)
opening_hours = models.OneToOneField(OpeningHours, on_delete=models.CASCADE, null=True)
description = models.CharField(max_length=2000, null=True)
phone = models.CharField(max_length=15, null=True)
parking_options = models.BooleanField(default=False)
which has a enum for kitchen_type:
KITCHEN_TYPE = [
(1, "Turkish"),
(2, "Italian"),
(3, "German"),
(4, "English"),
(5, "Indian"),
]
And this is the search function in view.py:
def search_result(request):
if request.method == "POST":
searched = request.POST['searched']
result = Restaurant.objects.filter(
Q(name__icontains=searched) | Q(address__city__icontains=searched))
return render(request, 'search_result.html', {'searched': searched, 'result': result})
else:
return render(request, 'search_result.html', {})
So how am I able to search for kitchen_type in the view?
CodePudding user response:
Instead of using a list of tuples I would recommend extending the IntegerChoices
or TextChoices
classes provided by Django. Here's an example of how you can use IntegerChoices
:
>>> class KitchenType(models.IntegerChoices):
... TURKISH = 1
... ITALIAN = 2
... GERMAN = 3
...
>>> if 1 in KitchenType:
... print(True)
...
True
https://docs.djangoproject.com/en/4.0/ref/models/fields/#enumeration-types