django在序列化器中的rest框架用户前缀

时间:2017-07-25 16:53:41

标签: python django django-rest-framework

models.py

address_choices = (("home":"Home"),("shop", "Shop"))
    class Address(models.Model):
       address_type = models.CharField(max_length=128, choices=address_choices)
       location = models.CharField(max_length=128)

forms.py

class AddressForm(forms.ModelForm):

   class Meta:
      model = Address


views.py


home_address = AddressForm(prefix="shop")
shop_address = AddressForm(prefix="home")

我可以在序列化程序中使用前缀,就像我在上面的表单中使用的那样

serializers.py

class AddressSerializers(serializers.ModelSerializer):

      class Meta:
         model = Address

views.py

home_serializer = AddressSerializers(prefix="home")
shop_serializer = AddressSerializers(prefix="shop")

1 个答案:

答案 0 :(得分:1)

如果您拥有当前型号Address,那么它就足以拥有一个序列化器。您可以在使用时指定{'address_type': 'home'}{'address_type': 'shop'}。如果您想拥有多个地址(批量创建),则应使用ListSerializermany=True参数(如果您在其他相关序列化程序中使用它)。