2017-05-08 80 views
0

我正在一個應用程序中,我需要構建一個API以將產品目錄返回給應用程序的客戶端,這就是我的模型的外觀。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(...) 
    . 
    . 
    . 

除公共字段(從Product在繼承)兩個模型產品A產品B與從彼此非常不同。 我想要做的是根據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

覆蓋APIView中的get_serializer_class方法。

然後訪問請求,做你的邏輯有:

#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'字段。如果是這種情況,那麼你會從請求中獲取數據。換句話說,客戶端將選擇和發送請求中的數據,您可以使用該數據來識別模型/ serizlalizer類型。 –

+0

@LuisAlbertoSantana如果數據不是來自請求,那麼你可以從客戶端向客戶端發送請求的api端點推斷出來,而不知道更多細節,我能做的最好的就是猜測你的具體用例 –