Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

988
Views
django rest framework: Obtenga la variable de ruta de URL en una vista

Tengo que pasar product_id (que es una cadena) a una vista. Allí tengo que hacer algunas operaciones de base de datos basadas en la identificación del producto. ¿Cómo puedo obtener esa identificación de producto en esa vista? En realidad, ¿cuál debería ser el parámetro en la vista de clase ProductDetailConfiguration ? Ahora estoy pasando viewsets.ModelViewSet . En realidad, esta llamada a la API no está completamente relacionada con ningún modelo.

# urls.py

 url(r'^product-configuration/(?P<product_id>[\w-]+)/$', views.ProductDetailConfiguration, name='product-configuration'),

# vistas.py

 class ProductDetailConfiguration(viewsets.ModelViewSet): queryset = Product.objects.all() def get_queryset(self, **kwargs): queryset = Product.objects.all() product_id = self.request.get('product_id', None) #filter query set based on the product_id return queryset serializer_class = ProductConfigurationSerializer
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Los parámetros de URL están disponibles en self.kwargs .
De la documentación :

Filtrado contra la URL

Otro estilo de filtrado podría implicar restringir el conjunto de consultas en función de alguna parte de la URL.

Por ejemplo, si su configuración de URL contenía una entrada como esta:

 url('^purchases/(?P<username>.+)/$', PurchaseList.as_view()),

A continuación, podría escribir una vista que devolviera un conjunto de consultas de compra filtrado por la parte del nombre de usuario de la URL:

 class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ This view should return a list of all the purchases for the user as determined by the username portion of the URL. """ username = self.kwargs['username'] return Purchase.objects.filter(purchaser__username=username)
about 4 years ago · Santiago Trujillo Report

0

Debe usar lookup_field en sus vistas para obtener product_id y la vista no debe pertenecer a ningún modelo. Aquí ya respondo una pregunta como la tuya usando django rest framework para devolver información por nombre

Espero que esto ayude a resolver su problema.

about 4 years ago · Santiago Trujillo Report

0

Este es mi enfoque:

Actualizar URL:

 url(r'^product-configuration$', views.ProductDetailConfiguration, name='product-configuration'),

En vista.py:

 class ProductDetailConfiguration(viewsets.ModelViewSet): lookup_field = 'product_id' serializer_class = ProductConfigurationSerializer def retrieve(request, product_id=None, *args, **kwargs): queryset = self.get_queryset() # Filter with produc_id # print(product_id) # Return Response
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!