Django: Arbitrary number of unnamed urls.py parameters

前端 未结 5 2135
面向向阳花
面向向阳花 2020-12-31 02:35

I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sub

5条回答
  •  余生分开走
    2020-12-31 02:44

    I think the answer of Adam is more generic than my solution, but if you like to use a fixed number of arguments in the url, you could also do something like this:

    The following example shows how to get all sales of a day for a location by entering the name of the store and the year, month and day.

    urls.py:

    urlpatterns = patterns('',
        url(r'^baseurl/location/(?P.+)/sales/(?P[0-9][0-9][0-9][0-9])-(?P[0-9][0-9])-(?P[0-9][0-9])/$', views.DailySalesAtLocationListAPIView.as_view(), name='daily-sales-at-location'),
    )
    

    Alternativly, you could also use the id of the store by changing (?P.+) to (?P[0-9]+). Note that location and sales are no keywords, they just improve readability of the url.

    views.py

    class DailySalesAtLocationListAPIView(generics.ListAPIView):
        def get(self, request, store, year, month, day):
            # here you can start using the values from the url
            print store
            print year
            print month
            print date
    
            # now start filtering your model
    

    Hope it helps anybody!

    Best regards,

    Michael

提交回复
热议问题