Мне нужны некоторые рекомендации по завершению настройки конечных точек api для моего поискового запроса в моих представлениях Django
Я пытаюсь завершить настройку search_query_set
для ArboristCompany в моих представлениях Django. Я слежу за документами Django-Haystack.
Я также использую DRF-Haystack. В документации показано, как настроить представления search_querty_set
с помощью файлов шаблонов. Однако у меня уже есть вызов API страницы поиска Vue JS.
В принципе, я хочу знать, как реализовать мой вызов API страницы поиска VueJS с помощью search_query_set
Конечной точки API в моих представлениях, как я это делал с вызовами API VueJS для конечных точек входа / регистрации API
Вот несколько файлов, которые могут быть вам полезны. serializers.py
class CompanySerializer(HaystackSerializer):
class Meta:
index_class = [ArboristCompanyIndex]
fields = [
'text', 'company_name', 'company_city', 'company_state'
]
search_indexes.py
class ArboristCompanyIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True)
company_name = indexes.CharField(model_attr='company_name')
company_city = indexes.CharField(model_attr='company_city')
company_state = indexes.CharField(model_attr='company_state')
# Instead of directly indexing company_price, use the price_display method
company_price_display = indexes.CharField(model_attr='price_display', null=True) # Using the custom price_display method
experience = indexes.CharField(model_attr='experience')
def get_model(self):
return ArboristCompany
def index_queryset(self, using=None):
return self.get_model().objects.filter(content='foo').order_by('company_name', 'company_city', 'company_state', 'experience')
просмотров
@authentication_classes([JWTAuthentication])
class LoginView(APIView):
def post(self, request, *args, **kwargs):
serializer = LoginSerializers(data=request.data, context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
login(None, user)
token = Token.objects.create(user=user)
return Response({"status": status.HTTP_200_OK, "Token": token.key})
if user is not None:
# Generate token
refresh = RefreshToken.for_user(user)
access_token = str(refresh.access_token)
return Response({
'message': 'Successful login',
'access_token': access_token,
'refresh_token': str(refresh),
}, status=status.HTTP_200_OK)
return Response({'error': 'Invalid email/password'}, status=status.HTTP_401_UNAUTHORIZED)
class RegisterView(APIView):
def post(self, request):
serializer = RegisterSerializer(data=request.data, context={'request': request})
if serializer.is_valid():
serializer.save()
return Response({
'message': 'successfully registered',
}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CompanySearchView(HaystackSerializer):
class Meta:
index_class = [ArboristCompanyIndex]
fields = [
'text', 'company_name', 'company_city', 'company_state'
]
def search_company(request):
index_classes = [ArboristCompany]
serializer_class = CompanySerializer
query = request.GET.get('q')
queryset = SearchQuerySet.filter(content='foo').order_by('company_name', 'company_city', 'company_state', 'experience')
И, наконец, urls.py (приложение)
from django.urls import path
from arborfindr.views import index
from .views import homeowner_info, review_info, services_info
from . import views
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
from .views import RegisterView, LoginView
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from rest_framework import routers
app_name = 'arborfindr'
#router = routers.DefaultRouter
#router.register('company/search', CompanySearchView, base_name='company-search')
urlpatterns = [
path('register/', RegisterView.as_view(), name='register'), # Register API endpoint url
path('login/', LoginView.as_view(), name ='login'), # Login API endpoint url
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('update_password/', views.update_password, name='update_password'),
path('homeowner_dashboard/', views.homeowner_dashboard, name='homeowner_dashboard'),
path('company_profile/', views.company_profile, name='company_profile'),
path('edit_homeowner_dashboard/', views.edit_homeowner_dashboard, name='edit_homeowner_dashboard'),
path('edit_company_profile/', views.edit_company_profile, name='edit_company_profile'),
path('arbor/review/', views.arbor_review, name='arbor_review'),
path('homeowner/', homeowner_info),
path('review_arbor/', review_info),
path('services/', services_info),
path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('arborfindr/', index),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)