zoukankan      html  css  js  c++  java
  • python orm create and update auto_now=True的触发

    class TypeBook(models.Model):
    # 创建时的默认存储位置和保管人
    storage_place = models.ForeignKey('StoragePlace', verbose_name=u'存储位置', null=True)
    admin = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)

    TypeBook.objects.create(admin=7)
    error: 报错 admin必须是一个对象
    right: TypeBook.objects.create(admin_id=7)

    TypeBook.objects.update(admin_id=7)
    error: 报错没有admin_id字段
    right: TypeBook.objects.update(admin=7)

    queryset.values('storage_place', 'admin').annotate(quantity=Count('id', distinct=True), id=Max('id'))
    FieldError: Cannot compute Count('id'): 'id' is an aggregate
    不可以重复聚合一个字段

    listapiview直接返回序列化后的数据,未有增加状态,所以增加一个mixin.py 创建个Response类

    class ResponseMixin(object):
    status_key = 'status'
    status_success = 1
    status_fail = 0
    data_key = 'data'
    error_key = 'error'

      def finalize_response(self, request, response, *args, **kwargs):
        response = super(ResponseMixin,
                         self).finalize_response(request, response, *args,
                                                 **kwargs)
        if response.exception:
            response = self.failed_response(response)
        else:
            response = self.success_response(response)
        return response
    
       def success_response(self, response):
        if isinstance(response.data, list) 
                or (isinstance(response.data, dict)
                    and self.status_key not in response.data.keys()):
            response.data = {
                self.status_key: self.status_success,
                self.data_key: response.data
            }
        return response
    
      def failed_response(self, response):
        if isinstance(response.data, dict) 
                and self.status_key not in response.data.keys():
    
            try:
                error_msg = response.data['detail']
            except KeyError:
                error_msg = response.data.get('error', 'error msg not set')
    
            response.data = {
                self.status_key: self.status_fail,
                self.error_key: error_msg
            }
    
            response.status_code = status.HTTP_200_OK
        return response
    

    物品类详情表

    class BooksOfTypeBookListAPIView(ResponseMixin, generics.ListAPIView):

    serializer_class = BooksSerializer
    
    def get_queryset(self):
        id = self.request.GET.get('type_book')
        type_book = TypeBook.objects.get(id=id, is_deleted=False)
        return type_book.books.filter(discard=False)
    
    def filter_queryset(self, queryset):
        storage_place_id = self.request.GET.get('storage_place')
        if storage_place_id:
            queryset = queryset.filter(storage_place_id=storage_place_id)
        admin_id = self.request.GET.get('admin')
        if admin_id:
            queryset = queryset.filter(admin_id=admin_id)
        return queryset
    

    def finalize_response(self, request, response, *args, **kwargs):
    response = super(TypeBookStatisticsAPIView, self).finalize_response(request, response, *args, **kwargs)
    if self.request.method in ['GET']:

            res = response.data['data']['results']
            for dic in res:
                dic['quantity'] = self.dic[dic['id']]['quantity']
            response.data['data']['results'] = res
        return response
    

    auto_now=True
    auto_now=True自动更新,有一个条件,就是要通过django的model层。
    如create或是save方法。
    如果是filter之后update方法,则直接调用的是sql,不会通过model层,就不会触发autu_now

  • 相关阅读:
    测试一面(宇宙条)
    java实现快速排序
    java实现冒泡排序
    Perl 获取当前系统时间
    日常问题解决:记一次因watchdog未启动导致的resin启动失败解决
    日常问题解决:记一次因信号量不足引起的APACHE启动错误解决以及kernel.sem值优化
    oracle11g使用expdp、impdp导出导入用户表结构
    日常问题解决:rhel6解决curl版本过旧问题
    日常问题解决:解决fork: retry: 资源暂时不可用
    日常问题解决:rhel7修改TCP最大连接数
  • 原文地址:https://www.cnblogs.com/robert-zhou/p/13856490.html
Copyright © 2011-2022 走看看