2016-11-11 7 views
1

ModelViewSetにデータベース内の別個のレコードのリストを取得するにはどうすればよいですか?ビューセットでカスタムリストを取得する方法

このモデルがあるとします。

class Animal(models.Model): 

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

とシリアライザ

class AnimalSerializer(serializers.ModelSerializer): 

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

およびビューセット。

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

私は、このような@list_route() などのデコレータとしてこのlinkが有用であることが分かったが、私はよくそれを理解することはできません。

私は別のAnimal.species_typeレコードのリストをビューセットから取得したいと考えています。助けてください。

答えて

1

フィルタリングにはいくつかのオプションがあります。あなたの要求/animals?species_type=MusMusculusを使って種の種類を送信し、あなたがビューにget_queryset()メソッドを乗り越えたときにそれを参照することができます。あなたのビューで

def get_queryset(self): 
    species = self.request.query_params.get('species_type', None) 
    if species is not None: 
     queryset = Animals.objects.all().distinct('species_type') 
     species = SpeciesSerializer(data=queryset) 
    return queryset 

シリアライザ

from rest_framework import serializers 
class Species(serializers.Serializer): 
    species_type = serializers.Charfield() 

代わりに、あなたは私が何を意味するか、先生ではありませんDjangoのフィルタフレームワークhttp://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend

+1

を採用することができ、私は関数を呼び出すしたいと思います私のデータベースにviewsetを介してすべてのdistinct_type_typeレコードを取得します。それは私が特定のspecies_typeを要求しないことを意味します。 –

+0

なので種だけでいいの?私は答えを編集しました – Dap

+0

それは、別のシリアライザクラスで定義できるということですか?素晴らしいと私は 'url_path'についてのアイデアが好きです。 –

関連する問題