flyEn'blog

所遇问题与解决方案(一)

  1. dict2.pop('name')删除并返回键为“name”的条目
  2. api视图里,request.data里包括request.POST and request.FILES
  3. api视图里request.query_params是request.GET更正确的表达(推荐)。
  4. netstat -anp
    netstat -tunlp
    ps -aux
    ps -aux|grep python

模版里如下

1
{% url 'hospital:disable_change' %}

中间不能有空格!

1
如果`{% url 'hospital: disable_change' %}`会报错:Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [ ](血的教训!)

字典遍历:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> for k,v in {'a':3,'b':4,'c':5}.items():
... print k,v
...
a 3
c 5
b 4
dic = {'a':3, 'b':4, 'c':5}
>>> for i, k in enumerate(dic):
... print i,k
...
0 a
1 c
2 b
>>> for i, k in enumerate(dic.items()):
... print i, k
...
0 ('a', 3)
1 ('c', 5)
2 ('b', 4)


1
2
id_list = CnRegion.objects.filter(parent_id=id).values_list('id', flat=True)
CnRegion.objects.filter(parent_id__in=id_list).update(is_able=True)

报错如下:

1
OperationalError: (1093, "You can't specify target table 'cn_region' for update in FROM clause")

解决方案:
debug出id_list的type其实不是list类型,

1
2
type(id_list)
<class 'django.db.models.query.ValuesListQuerySet'>

所以强转成list即可

1
CnRegion.objects.filter(parent_id__in=list(id_list)).update(is_able=True)

但是为什么直接执行查询可以得到queryest呢?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def weapp_login(code, encryptedData, iv):
"""
(在调用处捕获异常)调用微信服务器的接口,获取用户的信息

:return:用户解密信息的dict
"""
params = {"appid": app_id,
"secret": app_secret,
"js_code": code,
"grant_type": 'authorization_code'}
# 去微信服务器那里获取code
r = requests.request(method="get", params=params, url="https://api.weixin.qq.com/sns/jscode2session")
content = eval(r.content)
session_key = content['session_key']
logger.debug("登录开始:%s" % session_key )
decrpt_instanced = WXBizDataCrypt(appId=app_id, sessionKey=session_key)
user_info = decrpt_instanced.decrypt(encryptedData, iv)
return user_info

微信小程序登录


序列化器嵌套实现:

比如,pdf报告、与其项目指标各为都单独一张表,一个pdf报告里对应多个项目指标。
那么序列化器想输出pdf项目详情(内含其对应项目指标库)
方法一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class PDFItemsSerializers(serializers.ModelSerializer):
class Meta:
model = PDFItems
fields = __all__

class PDFItemsDetailSerializers(serializers.ModelSerializer):
pdf_items = serializers.SerializerMethodField()

class Meta:
model = PersonalHealth
fields = ("pdf_items",)

def get_pdf_items(self, obj):
query = PDFItems.objects.filter(status=0, personal_health=self.instance)
serializer = PDFItemsSerializers(query, many=True)
return serializer.data

方法二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class FilteredListSerializer(serializers.ListSerializer):

def to_representation(self, data):
data = data.filter(status=0)
return super(FilteredListSerializer, self).to_representation(data)

class PDFItemsSerializers(serializers.ModelSerializer):

class Meta:
model = PDFItems
list_serializer_class = FilteredListSerializer
fields = __all__

class PDFItemsDetailSerializers(serializers.ModelSerializer):
pdf_items = PDFItemsSerializers()


多对多关系

1
2
3
4
5
6
class Blog(StatusModel):
title = models.CharField(verbose_name='标题', max_length=50)
tag = models.ManyToManyField(Tag, related_name='under_tag_blog', verbose_name='标签')

class Tag(models.Model):
tag_name = models.CharField(verbose_name='分类名称', max_length=10)

增加:

因为 多对多会生成单个的一个表,所以其实不用 null=True, blank=True
假如tag表里有数据
b1 = Blog()
b1.title = ‘aaa’
b1.save() # 需要先保存对象才能再给tag值
tags = Tag.objects.all
b1.tag.add(tags[1]) # 保存单个tag对象用add
b1.tag = tags # 保存多个querset对象可直接赋值
b1.save() # 最后再保存

查询:

1
2
3
4
5
6
7
# 某博客的全部标签
b1 = Blog.objects.get(title='aaa')
b1.tags.all()
t1 = ...
t1.blog_set.all()
# 也可以用设置的反向查询属性查
t1.under_tag_blog.all()

Fork me on GitHub