2017-05-08 19 views
0

私は、製品カタログをアプリケーションのクライアントに返すためのAPIを構築する必要があるアプリケーションで作業しています。 (Productからinheritated)共通フィールドProductAとProductBが互いに非常に異なっている両方のモデルを除きDRF:フィールド値に基づいて動的にシリアライザクラスを選択

class Category(models.Model): 
    name = models.IntegerField(...) 
    description = models.CharField(...) 
    category_type = models.PositiveIntegerField(...) 
    . 
    . 
    . 

class Product(models.Model): 
    code = models.IntegerField(...) 
    category = models.ForeignKey(Category, ..) 
    . 
    # Common product fields 
    . 

class ProductA(Product): 
    product_a_field = models.IntegerField(..) 
    . 
    . 
    . 

class ProductB(Product): 
    product_b_field = models.IntegerField(...) 
    . 
    . 
    . 

。 私がしたいのは、Category.category_typeフィールドの値に基づいて、クライアントに異なる製品セットを送信することです。これを達成するためにどのような方法があります

class CategorySerializer(serializers.ModelSerializer): 
     . 
    def __init__(self, *args, **kwargs): 
     # 
     # Some code to select the product Serializer 
     # 

    products = ProductSerializer() 

    class Meta: 
     model = Category 
     fields = ('name', 'description', 'category_type', 'products') 

私はと私のカテゴリーシリアライザを簡素化したいと思いますか?私はPython3、Django 1.10、およびDRF 3.6を使用しています。

+0

がcategory_typeにアクセスするための可能な方法を追加しました。繰り返しますが、詳細がなくても、あなたが必要とするものを言うのは難しいです。 –

答えて

0

get_serializer_classメソッドをAPIViewでオーバーライドします。

次に要求にアクセスして、そこにあなたのロジックを実行します。

#taken directly from the docs for generic APIViews 
def get_serializer_class(self): 
    if self.request.user.is_staff: 
     return FullAccountSerializer 
    return BasicAccountSerializer 

をまた、あなたは、クラスベースのビューでは、このようなcategory_type変数にアクセスすることができます。

@property 
def category_type(self): 
    if not hasattr(self, '_category_tpye'): 
     self._category_type = Category.objects.get(attribute=self.kwargs['attribute']) 
    return self._category_type 
+0

APIViewはインスタンスにアクセスできますか?私はインスタンス属性に対してチェックする必要があります。 –

+0

@LuisAlbertoSantanaビューにはシリアライザへのアクセス権があります。シリアライザは、インスタンスにアクセスします。またはクエリーセットは、ターゲットモデルに明示的に関連付けられている必要があります。私はあなたが 'category_type'フィールドへのアクセス方法を尋ねようとしていると思います。そうであれば、リクエストからそのデータを取得します。言い換えれば、クライアントはモデル/セリライザタイプの識別に使用できるリクエストでデータを選択して送信します。 –

+0

@LuisAlbertoSantanaデータがリクエストから来ていない場合、クライアントが要求を送信しているAPIエンドポイントから推測できます。具体的な詳細を知らなくても、特定のユースケースを推測することができます –

関連する問題