跟上一节差不多
serializer
from .models import UserLeavingMessage, UserFav, UserAddress
class AddressSerialer(serializers.ModelSerializer):
user = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')
class Meta:
model = UserAddress
fields = ('user', 'province', 'city', 'district', 'address', 'signer_name', 'signer_mobile', 'add_time')
修改models.py
class UserAddress(models.Model):
"""
用户收货地址
"""
user = models.ForeignKey(User, verbose_name=u'用户', on_delete=models.CASCADE)
# 添加了省份和城市,为了方便前端调用
province = models.CharField(max_length=100, default="", verbose_name=u'省份')
city = models.CharField(max_length=100, default="", verbose_name=u'城市')
district = models.CharField(max_length=100, default="", verbose_name=u'区域')
address = models.CharField(max_length=100, default="", verbose_name=u'详细地址')
signer_name = models.CharField(max_length=100, default="", verbose_name=u'签收人')
signer_mobile = models.CharField(max_length=11, default="", verbose_name=u'电话')
add_time = models.DateTimeField(default=datetime.now, verbose_name=u'添加时间')
class Meta:
verbose_name = u'收货地址'
verbose_name_plural = verbose_name
views.py
class AddressViewset(viewsets.ModelViewSet):
"""
收货地址管理
list:
获取收货地址
create:
添加收货地址
update:
更新收货地址
delete:
删除收货地址
"""
serializer_class = AddressSerialer
permission_classes = (IsAuthenticated,)
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
def get_queryset(self):
return UserAddress.objects.filter(user=self.request.user)
说明: 因为这次增删改查都涉及到了。所以直接继承ModelViewSet就可以了 不用全部都写一遍过去
源码:
from .serializers import UserFavSerializer, UserFavDetailSerializer, LeavingMessageSerializer, AddressSerialer
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
"""
A viewset that provides default `create()`, `retrieve()`, `update()`,
`partial_update()`, `destroy()` and `list()` actions.
"""
pass
urls.py
from user_operation.views import UserFavViewset, LeavingMessageViewset, AddressViewset
#收货地址
router.register('address', AddressViewset, base_name='address')
程序效果:
第九章完结