在Django rest框架中过滤给定距离内的用户



我正在尝试在Django rest框架中实现一个自定义过滤器,它返回给定距离内的用户,我使用Django过滤器。我假设纬度和经度已经由前端提供。

这是我尝试过的。我不知道这样做是否正确。我有以下错误

'RenameAttributes' object is not iterable

我的代码

Views.py

def calculateDistance(lon1, lat1, lon2, lat2):
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
return 6371 * (
acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2))
)
class CustomFilter(django_filters.rest_framework.DjangoFilterBackend):
def filter_queryset(self, request , queryset,view):
alluser = queryset
newQueryset = []
distparam = request.GET.get('distance')
if distparam and bool(int(distparam)):
for user in alluser:
current_user_long = request.user.Longitude
current_user_lat = request.user.Latitude
alluser_long = user.Longitude
alluser_lat = user.Latitude
distance = calculateDistance(current_user_long, current_user_lat, alluser_long, alluser_lat)
if distance > distparam:
newQueryset.push(user)
return newQueryset
return queryset
class UserFilter(filters.FilterSet):
class Meta:
model = User
fields =['gender', 'last_name', 'first_name' ]
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
filterset_class = UserFilter
filter_backends = CustomFilter

Models.py

class User(AbstractUser):
username = None
email = models.EmailField(
max_length=100, verbose_name='email', unique=True)
gender = models.CharField(
max_length = 20,
choices = GENDER_CHOICES,
default = 'М'
)  
avatar= ProcessedImageField(upload_to='avatars',
processors=[ResizeToFill(400, 400), Watermark()],
format='JPEG',
options={'quality': 72})    
likes = models.ManyToManyField('User', blank=True, related_name="like")
latitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
longitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()

我认为这里出现的错误与距离计算/过滤无关,它可能是不正确的设置请确保DEFAULT_FILTER_BACKENDS是一个有效的元组或列表

相关内容

  • 没有找到相关文章

最新更新