2016-11-14 13 views
2

私はこれをviewsetと定義しています。species_typedistinct_speciesという別の動物を返すカスタム関数を作成したいと考えています。個別レコードを取得できません - Django w/Rest Framework

class AnimalViewSet(viewsets.ModelViewSet): 
    """ 
    This viewset automatically provides `list`, `create`, `retrieve`, 
    `update` and `destroy` actions. 
    """ 
    queryset = Animal.objects.all() 
    serializer_class = AnimalSerializer 

    @list_route() 
    def distinct_species(self, request): 
     query_set = Animal.objects.values('species_type').distinct() 
     serializer = self.get_serializer(query_set, many=True) 
     return Response(serializer.data) 

これは私のAnimalモデル

class Animal(models.Model): 

    this_id = models.CharField(max_length=25) 
    name = models.CharField(max_length=25) 
    species_type = models.CharField(max_length=25) 
    breed = models.CharField(max_length=25) 
    .... 

ですこれは私がここにルートを登録し、私のAnimalSerializer

class AnimalSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = Animal 
     fields = (
      'this_id', 
      'name', 
      'species_type', 
      'breed', 
      ... 
     ) 
     read_only_fields = ('id', 'created_at', 'updated_at') 

です。

# Create a router and register our viewsets with it. 
router = DefaultRouter() 
router.register(r'animal', AnimalViewSet) 

urlpatterns = [ 
    url(r'^api/', include(router.urls)), 
    url(r'^', IndexView.as_view(), name='index'), 
] 

しかし、私はこの/api/animal/distinct_species/

を行うときに、私はこのKeyError例外を得た:。

U」ガットKeyError例外 シリアライザAnimalSerializerにフィールドthis_idの値を取得しようとしたときの\ nシリアライザフィールドの名前が であり、dict インスタンスの属性またはキーと一致しない可能性があります。 \ n元の例外テキストは:u'this_id 'でした。

+0

'this_id'はモデルのpkである' id'フィールドとは異なりますが、 'this_id'はカスタム入力の別のIDです。 –

+0

あなたの動物モデルを追加し、this_idがどこから来るのかを説明してください – e4c5

+0

ある瞬間.. –

答えて

2

トラブルがこの1から茎:

query_set = Animal.objects.values('species_type').distinct() 

あなたquery_set今のオブジェクト辞書のリスト。

したがって、それはどのあなたのthis_idを持っていません[::、{ 'species_type' 'B'}、... { 'A' 'species_type'}] species_type

- 辞書は、1つのフィールドが含まれていますシリアライザが必要です。あなたはPostgreSQLの上にあった場合は、

第三の選択肢がために異なるシリアライザを作成することで呼び出す)第二の選択肢はvalues(中シリアライザに必要なすべてのフィールドを一覧表示することである

query_set = Animal.objects.distinct('species_type') 
にあなたのクエリを変更することができます distinct_speciesエンドポイントで使用すると、このシリアライザはModelSerializerになりません

+0

最初のオプションは私にこの1つを得ました、私はmysqlデータベース 'DISTINCT ONフィールドはこのデータベースのバックエンドによってサポートされていません 'を使用していますが、私はあなたの3番目のオプションを試してみたいです。 –

+0

はい、そのためにpostgresqlが必要だと言った理由です。 – e4c5

+0

3番目のオプションを作成するのは苦労します。これはdjangoに新しくなったので –

関連する問題