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

posted @ 2020-10-22 10:00  robertzhou  阅读(267)  评论(0编辑  收藏  举报