Как с помощью lookup's отфильтровать данные? Нужно выбрать из всех объявлений только релевантные по месту. Запрос типа GET /ad?location=Москва/.
Вот мои модели
from django.db import models
# Create your models here.
class Location(models.Model):
name = models.CharField(max_length=150)
lat = models.DecimalField(decimal_places=4, max_digits=6, null=True)
lng = models.DecimalField(decimal_places=4, max_digits=6, null=True)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Локация'
verbose_name_plural = 'Локации'
class User(models.Model):
ROLES = [
("member", "Пользователь"),
("moderator", "Модератор"),
("admin", "Админ"),
]
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
username = models.CharField(max_length=150, unique=True)
password = models.CharField(max_length=150)
role = models.CharField(max_length=50, choices=ROLES, default='member')
age = models.PositiveIntegerField()
locations = models.ManyToManyField(Location)
def __str__(self):
return self.username
class Meta:
verbose_name = 'Пользователь'
verbose_name_plural = 'Пользователи'
from django.db import models
# Create your models here.
from users.models import User
class Category(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
class Ads(models.Model):
name = models.CharField(max_length=150)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
price = models.PositiveIntegerField(null=True)
description = models.CharField(max_length=1000, null=True)
is_published = models.BooleanField(default=False)
image = models.ImageField(upload_to='ads/', null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Объявление'
verbose_name_plural = 'Объявления'
class AdsViewSet(ModelViewSet):
queryset = Ads.objects.all()
serializer_class = AdsSerializer
def list(self, request, *args, **kwargs):
if cats := request.GET.getlist("cat", None):
self.queryset = self.queryset.filter(category_id__in=cats)
if text := request.GET.get("text", None):
self.queryset = self.queryset.filter(name__icontains=text)
if location := request.GET.get("location", None):
self.queryset = self.queryset.filter(author__location__name__icontains=location)
При текущем коде выходит ошибка
django.core.exceptions.FieldError: Related Field got invalid lookup: users_location
[19/Aug/2022 22:26:52] "GET /ads/?location=%D0%BC%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 HTTP/1.1" 500 128950
Подскажите в чем моя ошибка и как правильно сделать