我想序列化一个有很多选择的模型:
class House(models.Model):
ACCESSIBILITY_CHOICES = (
(ACCESSIBILITY_FULL, 'Full'),
(ACCESSIBILITY_PARTIAL, 'Partial'),
(ACCESSIBILITY_NONE, 'None')
)
accessibility = models.IntegerField(max_length=1, choices=ACCESSIBILITY_CHOICES, null=True)
Run Code Online (Sandbox Code Playgroud)
我喜欢默认的序列化程序,例如:
class HouseView(generics.ListCreateAPIView):
model = House
serializer_class = HouseSerializer
class HouseSerializer(serializers.ModelSerializer):
class Meta:
model = House
Run Code Online (Sandbox Code Playgroud)
如果我只想要整数值,那么效果很好
{accessibility:1}
Run Code Online (Sandbox Code Playgroud)
但是,我想得到什么
{accessibility:'Full'}
Run Code Online (Sandbox Code Playgroud)
非常感谢帮助.非常感谢.
我有一个父对象和一对一相关的子模型,我想在父表示(read only)中渲染子平面的字段.目前,我已经通过自定义to_representation实现实现了这一点,但这似乎非常复杂,我想知道是否有更简单的方法来实现这一点.
由于我的相关模型是通过属性连接的,因此更加复杂.
所以这是具体的例子:默认情况下,相关对象将呈现为:
{
parent_name:'Bob',
child:{
name:'Alice'
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我想要的,目前得到我的to_representation:
{
parent_name:'Bob',
child_name:'Alice'
}
Run Code Online (Sandbox Code Playgroud)
我的模型看起来像这样:
class ChildModel(models.Model):
name = models.CharField(max_length=100, null=True)
class ParentModel(models.Model):
name = models.CharField(max_length=100, null=True)
_child = models.ForeignKey('ChildModel', null=True)
@property
def child(self):
return self._most_recent_status
@name.setter
def child(self, value):
self._child = value
Run Code Online (Sandbox Code Playgroud)
这是我的序列化器:
class FlatChildField(serializers.RelatedField):
def to_representation(self, value):
return value.name
class FlatParentSerializer(serializers.ModelSerializer):
parent_name = serializers.CharField(source='name', read_only=True)
child_name = FlatChildField(source='_child', read_only=True)
class Meta:
model = Parent
fields = ('name', 'child_name')
Run Code Online (Sandbox Code Playgroud)
对于更简单的解决方案来获得相关模型的平面表示,我将不胜感激.
为了完整起见,我很想知道是否有一个更简单的"正常"相关模型解决方案(即不是属性模型字段).我正在寻找相当于django模型的查询语法related_model__field …
我想知道Google Tasks API是否提供了将任务移动到其他列表的选项,或者我是否需要创建任务的副本.
移动方法似乎只允许在同一列表中移动.
我有一个带有布尔值字段的模型,我想用Django rest框架反序列化,并且我希望序列化程序在发布请求中缺少字段时抱怨。但是,事实并非如此。它默默地将缺少的布尔值解释为False。
class UserProfile(models.Model):
"""
Message between two users
"""
user = models.OneToOneField(User, verbose_name="django authentication user", related_name='user_profile')
newsletter = models.BooleanField(null=False)
research = models.BooleanField(null=False)
Run Code Online (Sandbox Code Playgroud)
使用以下序列化器创建模型:
class UserProfileSerializer(serializers.ModelSerializer):
research = BooleanField(source='research', required=True)
newsletter = BooleanField(source='newsletter', required=True)
class Meta:
model = UserProfile
fields = ('research', 'newsletter')
Run Code Online (Sandbox Code Playgroud)
在我看来,我还在创建用户,因此我有一些手动步骤:
def post(self, request, format=None):
userprofile_serializer = UserProfileSerializer(data=request.DATA)
reg_serializer = RegistrationSerializer(data=request.DATA)
phone_serializer = PhoneSerializer(data=request.DATA)
errors = {}
if userprofile_serializer.is_valid() and reg_serializer.is_valid() and phone_serializer.is_valid():
user = reg_serializer.save()
data = reg_serializer.data
user_profile = userprofile_serializer.object
user_profile.user = user
userprofile_serializer.save()
return …Run Code Online (Sandbox Code Playgroud) 我想ReconnectingClientFactory用 asyncio做一个。特别是处理客户端启动时服务器不可用的情况,在这种情况下ReconnectingClientFactory将继续尝试。这是asyncio.events.create_connection不做的事情。
具体来说:
该EchoClient例子就可以了。关键是如何建立连接。
factory = EchoClientFactory('ws://127.0.0.1:5678')
connectWS(factory)
Run Code Online (Sandbox Code Playgroud)
在扭曲版本的情况下ReconnectingClientFactory。
对比
factory = EchoClientFactory(u"ws://127.0.0.1:5678")
factory.protocol = SecureServerClientProtocol
loop = asyncio.get_event_loop()
# coro = loop.create_connection(factory, 'ws_server', 5678)
coro = loop.create_connection(factory, '127.0.0.1', 5678)
loop.run_until_complete(asyncio.wait([
alive(), coro
]))
loop.run_forever()
loop.close()
Run Code Online (Sandbox Code Playgroud)
或与asycnio版本类似。
问题在于,在 asyncio 版本中,asyncio.events.create_connection如果服务器不可用,连接是通过它建立的。
我该如何调和两者?
非常感谢
我希望大熊猫在被零除时引发异常,如下所示:
d = {'col1': [2., 0.], 'col2': [4., 0.]}
df = pd.DataFrame(data=d)
2/df
Run Code Online (Sandbox Code Playgroud)
代替当前结果:
0 1.000000
1 inf
Name: col1, dtype: float64
Run Code Online (Sandbox Code Playgroud)
任何建议如何实现这一目标?
我知道我可以使用numpy,np.seterr(divide='raise')但是熊猫确实忽略了这一点。
非常感谢
我使用requirejs和fastclick.我收到以下错误:
Uncaught TypeError: Cannot set property 'trackingClick' of undefined
Run Code Online (Sandbox Code Playgroud)
在Fastclick.js第30行,其中: this.trackingClick = false;
在config.js中我运行app.js:
require.config({
paths: {
fastclick:'fastclick'
}
)};
require(['app'], function (App) {
App.initialize();
});
Run Code Online (Sandbox Code Playgroud)
在我的app.js手中:
define(['fastclick'], function(fastclick){
var app = {
initialize: function () {
var attachFastClick = require('fastclick');
attachFastClick(document.body);
}
}
return app;
}
Run Code Online (Sandbox Code Playgroud)
浏览器启动正常,在调试器中快速单击库已正确实例化并解析但仍然this在Fastclick.js中无法解析.
我也试过,fastclick(document.body);但它似乎没有任何影响.
有任何想法吗?
我需要有一个长期运行的websocket客户端,它接收来自websocket服务器的推送消息,我需要监控客户端的连接状态:如果连接断开,我需要找出答案.
我的方法是定期记录一个常量字符串,并在未检测到日志消息时触发警报.
我的想法:1)有一个websocket客户端响应不规则传入的消息.2)同时有一个循环,当websocket客户端抛出一个ConnectionClosed执行时停止记录消息.
我对新的3.5异步语法很感兴趣.这个websocket实现特别基于asyncio.文档中的客户端看起来与我需要的完全一样.
但是,我不知道如何添加第二个coroutine来执行我的日志记录语句,并在websocket连接抛出ConnectionClosed时以某种方式停止.
这是开始对话的东西,但这不起作用,因为alive方法阻止事件循环.我正在寻找的是同时运行两种方法的优雅解决方案.
#!/usr/bin/env python
import asyncio
import logging
import websockets
logger = logging.getLogger(__name__)
is_alive = True
async def alive():
while is_alive:
logger.info('alive')
await asyncio.sleep(300)
async def async_processing():
async with websockets.connect('ws://localhost:8765') as websocket:
while True:
try:
message = await websocket.recv()
print(message)
except websockets.exceptions.ConnectionClosed:
print('ConnectionClosed')
is_alive = False
break
asyncio.get_event_loop().run_until_complete(alive())
asyncio.get_event_loop().run_until_complete(async_processing())
Run Code Online (Sandbox Code Playgroud) python ×3
django ×2
autobahn ×1
cordova ×1
fastclick.js ×1
google-tasks ×1
pandas ×1
python-3.x ×1
requirejs ×1
websocket ×1