0

Animal、Cat、Dogの3つのモデルがあると仮定します。ここで、CatとDogは親クラスAnimalから継承します。djangoでリストシリアライザを使用して継承されたシリアライザに従ってシリアライズするにはどうすればよいですか?

class Animal: 
    name 
class Cat: 
    sleep_hours 
class Dog: 
    breed 

sleep_hoursおよびbreedはそれぞれ猫および犬の相互排他的特性であると考える。今、私たちは、シリアライザ持っている: -

AnimalSerializer: 
    name 
CatSerializer(AnimalSerializer): 
    sleep_hours 
DogSerializer(AnimalSerializer): 
    breed 



Now we want to develop an API where we return all the information about animal so it should return something like this 
[ 
{'tommy', 'pug'}, 
{'kitty', '10'}, 
] 
So consider animal class is linked to user i.e. user.animals returns a list of animals (parent class) we want to use modelSerialiser on user. 
class UserAnimalSerializer(serializers.ModelSerializer): 
    animals = AnimalSerializer(read_only=True) 

class Meta: 
     model = User 
     fields = ('animals') 

Now we want to use different serializer(child serializer) based on the instance type. Is there any good way to handle these type of scenarios. Please comment if there is some confusion about the question. 

答えて

0

をこれがデザインパターンソリューションではありませんが、なぜシリアライザは(誰かがイテレータパターンを言いました;-)?)フィールドを反復処理し、それらをシリアル化していませんか?なぜ子シリアライザが必要ですか?
シリアライザですべてのフィールドをシリアル化する必要がない場合は、各動物子にの配列を指定してシリアル化可能なフィールドを指定してからシリアル化します。
このソリューションでは、という動物のすべてのサブクラスに対して1つのシリアライザを使用できます。です。

関連する問題