用户收藏 是属于用户操作行为
所以要写到 user_operation
C:\Users\huang\PycharmProjects\MxShop\apps\user_operation\serializers.py
from rest_framework import serializers
from .models import UserFav
class UserFavSerializer(serializers.ModelSerializer):
class Meta:
model = UserFav
fields = ("user", "goods")
C:\Users\huang\PycharmProjects\MxShop\apps\user_operation\views.py
from rest_framework import viewsets
from rest_framework import mixins
from .models import UserFav
from .serializers import UserFavSerializer
class UserFavViewset(mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
"""
用户收藏功能
"""
queryset = UserFav.objects.all()
serializer_class = UserFavSerializer
第三步:
"""MxShop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
# from django.contrib import admin
# from django.urls import path
from django.conf.urls import url, include
import xadmin
from MxShop.settings import MEDIA_ROOT
from django.views.static import serve
from rest_framework.documentation import include_docs_urls
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views
from rest_framework_jwt.views import obtain_jwt_token
from goods.views import GoodsListViewSet, CategoryViewSet
from users.views import SmsCodeViewset, UserViewset
from user_operation.views import UserFavViewset
router = DefaultRouter()
# 配置 goods 的url
router.register(r'goods', GoodsListViewSet)
# 配置 category 的url
router.register(r'categorys', CategoryViewSet)
# 配置
router.register(r'code', SmsCodeViewset, base_name="code")
router.register(r'users', UserViewset, base_name="users")
router.register(r'userfavs', UserFavViewset, base_name="userfavs")
urlpatterns = [
# path('admin/', admin.site.urls),
url(r'^xadmin/', xadmin.site.urls),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^media/(?P.*)$', serve, {"document_root": MEDIA_ROOT}),
# 商品列表页
# url(r'goods/$', goods_list, name="goods-list"),
url(r'^', include(router.urls)),
url(r'docs/', include_docs_urls(title="木星")),
# drf自带的token认证模式
url(r'^api-token-auth/', views.obtain_auth_token),
# jwt的认证接口
# url(r'^jwt_auth/', obtain_jwt_token),
url(r'^login/', obtain_jwt_token),
]
效果:
现在的逻辑是 用户可以选择,是不对的。
默认的应该是登录用户
https://www.django-rest-framework.org/api-guide/validators/#currentuserdefault
owner = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
效果:
现在只显示商品
选择一个商品,然后 POST 一下
报错:
ValueError at /userfavs/
Cannot assign "": "UserFav.user" must be a "UserProfile" instance.
Request Method: POST
Request URL: http://localhost:8000/userfavs/
Django Version: 1.11
Exception Type: ValueError
Exception Value:
Cannot assign "": "UserFav.user" must be a "UserProfile" instance.
Exception Location: D:\Envs\MxShop\lib\site-packages\django\db\models\fields\related_descriptors.py in __set__, line 216
Python Executable: D:\Envs\MxShop\Scripts\python.exe
Python Version: 3.6.0
Python Path:
['C:\\Users\\huang\\PycharmProjects\\MxShop\\extra_apps',
'C:\\Users\\huang\\PycharmProjects\\MxShop\\apps',
'C:\\Users\\huang\\PycharmProjects\\MxShop',
'C:\\Users\\huang\\PycharmProjects\\MxShop',
'C:\\Program Files\\JetBrains\\PyCharm 2018.2.4\\helpers\\pydev',
'C:\\Users\\huang\\PycharmProjects\\MxShop',
'C:\\Users\\huang\\PycharmProjects\\MxShop\\apps',
'C:\\Users\\huang\\PycharmProjects\\MxShop\\extra_apps',
'C:\\Program Files\\JetBrains\\PyCharm 2018.2.4\\helpers\\pydev',
'C:\\Users\\huang\\.PyCharm2018.2\\system\\cythonExtensions',
'D:\\Envs\\MxShop\\Scripts\\python36.zip',
'C:\\Users\\huang\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
'C:\\Users\\huang\\AppData\\Local\\Programs\\Python\\Python36\\lib',
'C:\\Users\\huang\\AppData\\Local\\Programs\\Python\\Python36',
'D:\\Envs\\MxShop',
'D:\\Envs\\MxShop\\lib\\site-packages',
'D:\\Envs\\MxShop\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg',
'C:\\Program Files\\JetBrains\\PyCharm '
'2018.2.4\\helpers\\pycharm_matplotlib_backend']
Server time: 星期日, 5 五月 2019 14:58:32 +0800
这个问题没有解决
接着往下看
加上:
mixins.ListModelMixin
刷新页面:
点击发送:
就删除了 id为1 的收藏
现在的同一个商品可以收藏多次,需要改进
unique_together = ("user", "goods")
先把收藏表清空,然后同步表,
makemigrations
migrate
现在同一个商品再次收藏 就会报错:
{
"non_field_errors": [
"字段 user, goods 必须能构成唯一集合。"
]
}
还有一种方法:
https://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator
validators = [
UniqueTogetherValidator(
queryset=UserFav.objects.all(),
fields=('user', 'goods')
)
]