Django继承从基类获取typeof子

时间:2016-11-22 18:13:34

标签: django django-rest-framework

我有三个模型如下:

from model_utils.managers import InheritanceManager

class Product(models.Model):
    name = models.CharField(max_length=50, blank=False, verbose_name="Type here name",)

class Pub(Product):
    product = models.OneToOneField(Product, parent_link=True, )
    seating_capacity = models.IntegerField(null=False, verbose_name="Seating capacity of the Pub",)

class Restaurant(Product):
   product = models.OneToOneField(Product, parent_link=True, )
   food_speciality = MultiSelectField(choices = MY_CHOICES)

我已经实现了django-cart并附加了Product作为我的产品型号。我将所有产品退回到我的前端。这基本上只将产品特定属性的产品对象发送到前端,因此很难区分哪个产品是Pub,哪个是Restaurant。

如何在后端处理此问题?有没有办法提取/发送产品类型?

这就是我的观点:

@api_view(('GET',))
def show(request):
    cart = Cart(request.session)
    products = cart.products
    serializer = ProductSerializer(products, many=True)
    return Response(serializer.data)

它返回例如:

[{"id":1,"name":"Shreyas","price":"45000.00000","avg_user_rating":"4.50000","city":1},{"id":4,"name":"Phadake","price":"350.00000","avg_user_rating":"5.00000","city":2}] 

串行:

class ProductSerializer(serializers.ModelSerializer):
    category = serializers.ReadOnlyField()
    class Meta:
            model = Product
            fields = '__all__'

1 个答案:

答案 0 :(得分:1)

选项1

Metaverbose_name添加到模型中:

class Pub(Product):
    product = models.OneToOneField(Product, parent_link=True, )
    seating_capacity = models.IntegerField(null=False, verbose_name="Seating capacity of the Pub",)

    class Meta:
        verbose_name = 'Pub'

class Restaurant(Product):
    product = models.OneToOneField(Product, parent_link=True, )
    food_speciality = MultiSelectField(choices = MY_CHOICES)

    class Meta:
        verbose_name = 'Restaurant'

将这些行添加到ProductSerializer

category = serializers.SerializerMethodField()

def get_category(self, obj):
    return obj._meta.verbose_name

选项2

或者,您可以为每个模型添加property

class Pub(Product):
    product = models.OneToOneField(Product, parent_link=True, )
    seating_capacity = models.IntegerField(null=False, verbose_name="Seating capacity of the Pub",)

    @property
    def category(self):
        return 'Pub'

class Restaurant(Product):
    product = models.OneToOneField(Product, parent_link=True, )
    food_speciality = MultiSelectField(choices = MY_CHOICES)

    @property
    def category(self):
        return 'Restaurant'

然后将此行添加到ProductSerializer

category = serializers.ReadOnlyField()

选项3

当然,如果您不想将Meta或属性添加到模型中,也可以选择执行此操作:

def get_category(self, obj):
    return obj.__class__.__name__

但是你会有限制,每个类别都等于班级名称,这可能是个问题。