DRF oneToOneField创建序列化程序

时间:2017-02-18 12:03:02

标签: python django serialization django-rest-framework

尝试使用drf / create serizlizer创建一些嵌套模型。

我正在尝试序列化的是'TradePost'模型,其中包含post和ProductItem。

我已经使用了'ProductItemSerializer'和'PostSerializer'..我怎么能序列化它们?与创作?不是通过pk值告诉现有记录。

models.py

class ProductItem(models.Model):
    baseProduct = models.ForeignKey(Product, related_name='baseProduct')

    seller = models.ForeignKey(User)

    price = models.DecimalField(max_digits=6, decimal_places=2)

    isOrderClosed = models.BooleanField()
    isTradeCompleted = models.BooleanField()


    def __str__(self):
        return '[seller = '+self.seller.username+']' + '[product = '+(str)(self.baseProduct)+']' + '[id = '+(str)(self.id)+']'




class TradePost(models.Model):

    basePost = models.OneToOneField(Post)

    baseProductItem = models.OneToOneField(ProductItem)

    def __str__(self):
        return '[post = ' + (str)(self.basePost) + ']' + '[product = ' + (str)(self.baseProductItem) + ']' + '[id = ' + (str)(self.id) + ']'

in serialziers.py

class ProductItemCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductItem
        fields = ('baseProduct', 'price')



#???
class TradePostCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = TradePost
        fields = ('basePost', 'baseProductItem',)

    def create(self, validated_data):
        post =

2 个答案:

答案 0 :(得分:0)

您可以使用序列化程序来表示字段,例如

class TradePostCreateSerializer(serializers.ModelSerializer):
    basePost = PostSerializer()
    baseProductItem = ProductItemSerializer()

    class Meta:
        model = TradePost
        fields = ('basePost', 'baseProductItem',)

参考:

DRF Nested relationships

如果您正在寻找可写的嵌套序列化程序

Writable nested serializers

答案 1 :(得分:0)

writable nested serializer类似,你可以尝试这样的事情:

class TradePostCreateSerializer(serializers.ModelSerializer):
    basePost = PostCreateSerializer()
    baseProductItem = ProductItemCreateSerializer()

    class Meta:
        model = TradePost
        fields = ('basePost', 'baseProductItem',)

    def create(self, validated_data):
        # pop out the dict to create post and item, depend on whether you want to create post or not
        post = validated_data.get('basePost')
        product = validated_data.get('baseProductItem')
        # create post first
        trade_post = None
        post_obj = Post.objects.create(**post)
        if post_obj:
            # create product item
            prod_item = ProductItem.objects.create(basePost=post_obj, **product)
            trade_post = TradePost.objects.create(baseProduct=prod_item, **validated_data)
        return trade_post

对于python,请遵循命名约定并使用lower_case_with_underscores,如base_productbase_post,这将更容易阅读