【问题标题】:How to retrieve object by foreign key in the url using Django and rest_framework如何使用 Django 和 rest_framework 通过 url 中的外键检索对象
【发布时间】:2013-09-03 01:19:42
【问题描述】:

假设我正在使用两个简单的模型:

class Location(models.Model):
    location_name = models.CharField(max_length=100)
    country = models.ForeignKey("Country")

class Country(models.Model):
    country_name = models.CharField(max_length=100)

为了通过它的主键检索对象,我定义了这样的视图和 URL (related to my resolved question):

url(r'^location/(?P<pk>[0-9]+)/$', views.LocationDetailAPIView.as_view(), name='location-detail'),
url(r'^country/(?P<pk>[0-9]+)/$', views.CountryDetailAPIView.as_view(), name='country-detail')

现在我想定义一个新视图,它返回一个国家/地区所有位置/城市的列表。我的想法是使用下面的 url 定义(或类似的)。

url(r'^location-by-country/(?P<country_pk>[0-9]+)/$', views.LocationByCountryListAPIView.as_view(), name='location-by-country-detail')

我一直在寻找答案,但可能我没有使用正确的关键字。我将如何实现我的视图以使用来自 url 的外键?我可以使用过滤器按 country_pk 过滤位置吗?

编辑:这是我想出的,但我不知道如何过滤外键:

class LocationByCountryIdAPIView(generics.GenericAPIView):        
    def get(self, request, country_pk):
        locations = Location.objects.all() # .filter(???)
        location_list = list()
        for location in locations:
            # now I would do something similar to this
            # or use a filter on locations instead of creating location_list 
            # and appending locations to it
            if location.country.pk == country_pk:
                location_list.append(location)        

        location_serializer = LocationSerializer(location_list, many=True)
        # or location_serializer = LocationSerializer(locations, many=True) when using filter

        return Response({
            'locations': location_serializer.data
        })

最好的问候, 迈克尔

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    好的,现在我自己运行了。事情是这样的:

    class LocationByCountryListAPIView(generics.ListAPIView):
        def get(self, request, country_pk):
            # get the country by its primary key from the url
            country = Country.objects.get(pk=country_pk)
    
            locations = Location.objects.filter(country=country)
            location_serializer = LocationSerializer(locations, many=True)
    
            return Response({
                'locations': location_serializer.data
            })
    

    我使用的是上面提到的url定义:

    url(r'^location-by-country/(?P<country_pk>[0-9]+)/$', views.LocationByCountryListAPIView.as_view(), name='location-by-country-detail')
    

    无论如何,我不确定这个解决方案是否是最好的方法。对于如何改进我的解决方案,我将不胜感激。

    最好的问候, 迈克尔

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-09
      • 2010-10-15
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 2012-05-11
      • 1970-01-01
      相关资源
      最近更新 更多