pythondjango-modelsdjango-views

How do I resolve a FieldError(Cannot resolve keyword '...' into field.) in Django?


I am trying to have clients search for service providers in my search.html stored in the database that only belong to a specific category of services.

This is the snippet from the template handling the search:

<form method="get" action="{% url 'search' %}">
  <select name="category" id="category">
    <option value="">Select a category</option>
    {% for category_key, category_name in service_categories %}
    <option value="{{ category_key }}">{{ category_name }}</option>
    {% endfor %}
  </select>
 <button type="submit">Search</button>
</form>

This is the current logic in the views.py for the search template.

def search(request):
    # Capture search criteria from request parameters
    category = request.GET.get('category')
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')

    # Initialize search results
    search_results = None

    if category or (start_time and end_time):
        # Filter providers based on category and availability
        query = ServiceProvider.objects.all()
        if category:
            query = query.filter(services__category=category)
        if start_time and end_time:
            try:
                start_time = datetime.strptime(start_time, '%Y-%m-%dT%H:%M:%S')
                end_time = datetime.strptime(end_time, '%Y-%m-%dT%H:%M:%S')
                query = query.filter(
                    availabilities__start_time__lte=end_time,
                    availabilities__end_time__gte=start_time
                )
            except Exception as e:
                print(f"Error processing availability: {e}")
        search_results = query.distinct()

    # Fetch Popular or Featured Providers (modify based on your logic)
    popular_providers = ServiceProvider.objects.filter(is_featured=True)[:3]

    service_categories = Service.service_categories

    context = {
        'search_results': search_results,
        'popular_providers': popular_providers,
        'service_categories': service_categories
    }

    return render(request, 'search.html', context)

These are the related models for ServiceProvider and Service:

class ServiceProvider(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='service_provider')
    location = models.CharField(max_length=255)
    average_rating = models.FloatField(default=0.0, validators=[MinValueValidator(0.0), MaxValueValidator(5.0)])
    name = models.CharField(max_length=255, default='Provider name')
    image_url = models.URLField(blank=True)  # Optional field for service provider image URL
    description = models.TextField(blank=True)  # Optional field for service provider description
    offers = models.TextField(blank=True)  # Field to store offered services (comma-separated or JSON format)
    pricing = models.TextField(blank=True)  # Field to store pricing information (text or JSON format)
    availability_description = models.TextField(blank=True)  # Text field for general availability info (e.g., "Weekdays 9am-5pm")
    is_featured = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username
class Service(models.Model):
    service_categories = [
        ('Dance', 'Dance'),
        ('Music', 'Music'),
        ('MC', 'Master of Ceremonies'),
        # Add more categories as needed
    ]
    name = models.CharField(max_length=255)
    provider = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='services')
    location = models.CharField(max_length=255, default='')
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    category = models.CharField(max_length=50, choices=service_categories)

    def __str__(self):
        return f"{self.name} by {self.provider.user.username}"

So the error came from this particular line query = query.filter(category__services=category) in the views.py. I decided to post the full code of the view function for context.

I was expecting the code to return a list of service providers under a particular category, for example, 'Dance' but instead raised this error:

Cannot resolve keyword 'services' into field. Choices are: availabilities, availability_description, average_rating, description, id, image_url, is_featured, location, name, offers, pricing, user, user_id

I have a feeling the issue could be something small but I've personally failed to figure it out.

PS: Apologies if I've provided a lot of unnecessary code, it's my first time posting a question here. Also, if there is any more explanation required, I can provide it.


Solution

  • you bind Service to settings.AUTH_USER_MODEL with foreign key. you bind ServiceProvider to settings.AUTH_USER_MODEL with foreign key.

    Direct in you code the query should be like:

    query = ServiceProvider.objects.filter(user__services__category=category)