序列化相关模型并覆盖create方法

时间:2017-07-11 10:07:40

标签: python django django-rest-framework

我是DRF的新手,我想做一些与django表格中的表格相似的东西 我有一个InvoiceProducts相互关联的模型会抛出多个InvoiceDetail模型..当我创建一个发票时,我会选择一些产品并创建一个InvoiceDetail对象对于每个..我想在DRF中这样做我怎么能序列化Invoice模型然后它的创建函数呢? 或者我应该从视图中做到这一点?

models.py:

 class Invoices(models.Model):
     #some fields
     products = models.ManyToManyField('Products', through='InvoiceDetail')


class Products(models.Model):
    #some fields


class InvoiceDetail(models.Model):
    invoice = models.ForeignKey(Invoices, related_name='parent_invoice')
    product = models.ForeignKey(Products, related_name='parent_product')
    product_description = models.TextField()
    product_price = models.DecimalField(max_digits=9, decimal_places=2)
    quantity_sold = models.IntegerField()

serializers.py:

class ProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Products
        fields = ('barcode', 'product_code', 'name', 'description', 'category',
                  'quantity_in_stock', 'quantity_on_hold', 'expire_date',
                  'vendor', 'manufacturer', 'discount')


class InvoiceDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = InvoiceDetail
        fields = '__all__'

view.py:

class ProductsView(viewsets.ReadOnlyModelViewSet):
    queryset = Products.objects
    serializer_class = ProductsSerializer


class InvoicesView(viewsets.ModelViewSet):
    queryset = Invoices.objects
    serializer_class = InvoicesSerializer



class InvoiceDetailView(viewsets.ModelViewSet):
    queryset = InvoiceDetail.objects
    serializer_class = InvoiceDetailsSerializer

1 个答案:

答案 0 :(得分:1)

您可以在序列化程序本身中执行此操作,

class InvoiceSerializer(serializers.ModelSerializer):
    products = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), many=True)
    class Meta:
        model = Invoice
        fields = [ f.name for f in model._meta.fields ] + ['products']

    def create(self, validated_data):
        products = validated_data.pop('products')
        invoice = super(InvoiceSerializer, self).create(validated_data)
        for product in products:
            InvoiceDetail.objects.create(invoice=invoice, product=product)
        return invoice

这只是了解其工作原理的基本示例。您可以根据需要自定义它。