Hi everyone,
I’m new to Django and web development, coming from a background of Data Engineering. I’m running into a problem (probably very basic to an expert) while I’m creating a simple application which displays Services offered by Shops. I’ve solved the problem but I want to know if I’m doing things efficiently.
Here is my models.py (simplified version):
from django.db import models
# Represent a shop that offers services
class Shop(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
# Represents the services offered
class Service(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
shop = models.ManyToManyField(Shop, related_name='shop_services')
def __str__(self):
return self.name
Context :
On my home view I have a search bar, which allows users to look up a service like ‘Cleaning’. When the user submits text here, I have a reverse filter through the Shops model to find all the shops which provide the service related to what was searched. Then on the search view, I am iterating through shops and then another iteration through all the services to find all the related services. I basically want to show cards with each applicable shop with their associated service and price.
The problem area, looking for suggestions to improve:
I want to be able to display all related services offered by a shop in one card, rather than creating a new card for every shop-service combination. So is my model design correct? Are there long term efficiency issues that can arise when the data size increase?
Here is my views.py:
def home(request):
if request.method == 'POST':
# Fetching the requested service
service_name = request.POST.get('service_name')
return redirect('search', service_name = service_name)
else:
return render(request, template_name='main/home.html', {})
def search(request, service_name):
shops = Shop.objects.filter(shop_services__name__icontains = service_name).distinct()
return render(request, 'main/search.html', context = {'searched' : service_name, 'shops_found': shops})