我正在编写一个食谱组织者作为课程的示例项目.除了使用一些非常基本的功能之外,我对DRF不是很有经验.这是目标:
使用相关成分创建新配方.在创建Recipe对象的同时创建Ingredient对象.
models.py:
class Ingredient(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True, null=True, help_text="This is a quick description of your recipe")
directions = models.TextField(help_text="How to make the recipe")
ingredients = models.ManyToManyField(Ingredient)
def __str__(self):
return self.name
Run Code Online (Sandbox Code Playgroud)
serializers.py
class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredient
class RecipeSerializer(serializers.ModelSerializer):
ingredients = IngredientSerializer(many=True)
class Meta:
model = Recipe
def create(self, validated_data):
ingredients_data = validated_data.pop('ingredients')
recipe = Recipe.objects.create(**validated_data)
for ingredient_data in ingredients_data:
Ingredient.objects.create(**ingredient_data)
return recipe
Run Code Online (Sandbox Code Playgroud)
这样可以在数据库中成功创建Recipe对象和Ingredients对象,但不会将Ingredients列表与Recipe关联.我认为这是因为当我运行时ingredients_data = …
Jinja允许我这样做
{% for item in all_items %}
{{ item }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
但我希望能够只采取前n项; 在Python中将是
for item in all_items[:n]:
Run Code Online (Sandbox Code Playgroud)
在Jinja有没有优雅的方法来做到这一点,除了
{% for item in all_items %}
{% if loop.index <= n %}
{{ item }}
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud) 如何使用变量格式化变量?
cart = {"pinapple": 1, "towel": 4, "lube": 1}
column_width = max(len(item) for item in items)
for item, qty in cart.items():
print "{:column_width}: {}".format(item, qty)
> ValueError: Invalid conversion specification
Run Code Online (Sandbox Code Playgroud)
要么
(...):
print "{:"+str(column_width)+"}: {}".format(item, qty)
> ValueError: Single '}' encountered in format string
Run Code Online (Sandbox Code Playgroud)
但是,我能做的是首先构造格式化字符串然后格式化它:
(...):
formatter = "{:"+str(column_width)+"}: {}"
print formatter.format(item, qty)
> lube : 1
> towel : 4
> pinapple: 1
Run Code Online (Sandbox Code Playgroud)
然而,看起来很笨拙.是不是有更好的方法来处理这种情况?
我有一堆规则分布的点(θ= n*π/ 6,r = 1 ... 8),每个点的值都为[0,1].我可以使用matplotlib中的值来绘制它们
polar(thetas, rs, c=values)
Run Code Online (Sandbox Code Playgroud)
但是,只有一个微小的点,我想用相应的"细胞"(即所有东西,直到相邻点的中间),使用与点的值相对应的颜色:

(注意,这里我的值只是[0,.5,1],实际上它们将是介于0和1之间的所有东西.是否有任何直接的方法来实现这个(或者足够接近的东西)matplotlib?也许它更容易把它想象成2D直方图?
有没有办法告诉setuptools或分发需要特定平台上的包?
在我的特定情况下,我正在使用readline,它是Unix系统上标准库的一部分,但在Windows上我需要pyreadline模块来替换该功能(参见这个问题).如果我只是把它放在要求中它也安装在Unix系统上,它完全没用.
简而言之:检查python中的巨大列表是否已更改的禁区方法是什么?hashlib需要一个缓冲区,并且构建该列表的字符串表示是不可行的.
总之:我有一个巨大的字典列表代表数据.我对这些数据进行了大量分析,但是所有分析都需要一些元数据方面,即.主题集(列表中的每个词典都有一个主题键,有时我只需要一个列表,其中包含数据集中存在数据的所有主题.).所以我想实现以下内容:
class Data:
def __init__(self, ...):
self.data = [{...}, {...}, ...] # long ass list of dicts
self.subjects = set()
self.hash = 0
def get_subjects(self):
# recalculate set of subjects only if necessary
if self.has_changed():
set(datum['subject'] for datum in self.data)
return self.subjects
def has_changed(self):
# calculate hash of self.data
hash = self.data.get_hash() # HOW TO DO THIS?
changed = self.hash == hash
self.hash = hash # reset last remembered hash
return changed
Run Code Online (Sandbox Code Playgroud)
问题是如何实现该has_changed方法,或者更具体地说,get_hash(每个对象已经有一个 …
我在Windows上创建了一个pickle对象(一个包含几个numpy数组的列表),显然保存到以文本形式加载的文件中,而不是二进制模式(即open(filename, 'w')代替open(filename, 'wb')).结果是现在我不能解开它(甚至不在Windows上),因为它感染了\r字符(可能还有更多)?主要的抱怨是
ImportError: No module named multiarray
Run Code Online (Sandbox Code Playgroud)
据说是因为它正在寻找numpy.core.multiarray\r,当然不存在.简单地删除\r字符没有做到这一点(尝试了两个sed -e 's/\r//g',在python中s = file.read().replace('\r', ''),但两个都打破了文件,cPickle.UnpicklingError稍后产生)
问题是我真的需要从对象中获取数据.任何想法如何修复文件?
编辑:根据要求,我的文件的前几百个字节,八进制:
\x80\x02]q\x01(}q\x02(U\r\ntotal_timeq\x03G?\x90\x15r\xc9(s\x00U\rreaction_timeq\x04NU\x0ejump_directionq\x05cnumpy.core.multiarray\r\nscalar\r\nq\x06cnumpy\r\ndtype\r\nq\x07U\x02f8K\x00K\x01\x87Rq\x08(K\x03U\x01<NNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tbU\x08\x025\x9d\x13\xfc#\xc8?\x86Rq\tU\x14normalised_directionq\r\nh\x06h\x08U\x08\xf0\xf9,\x0eA\x18\xf8?\x86Rq\x0bU\rjump_distanceq\x0ch\x06h\x08U\x08\x13\x14\xea&\xb0\x9b\x1a@\x86Rq\rU\x04jumpq\x0ecnumpy.core.multiarray\r\n_reconstruct\r\nq\x0fcnumpy\r\nndarray\r\nq\x10K\x00\x85U\x01b\x87Rq\x11(K\x01K\x02\x85h\x08\x89U\x10\x87\x16\xdaEG\xf4\xf3?\x06`OC\xe7"\x1a@tbU\x0emovement_speedq\x12h\x06h\x08U\x08\\p\xf5[2\xc2\xef?\x86Rq\x13U\x0ctrial_lengthq\x14G@\t\x98\x87\xf8\x1a\xb4\xbaU\tconditionq\x15U\x0bhigh_mentalq\x16U\x07subjectq\x17K\x02U\x12movement_directionq\x18h\x06h\x08U\x08\xde\x06\xcf\x1c50\xfd?\x86Rq\x19U\x08positionq\x1ah\x0fh\x10K\x00\x85U\x01b\x87Rq\x1b(K\x01K\x02\x85h\x08\x89U\x10K\xb7\xb4\x07q=\x1e\xc0\xf2\xc2YI\xb7U&\xc0tbU\x04typeq\x1ch\x0eU\x08movementq\x1dh\x0fh\x10K\x00\x85U\x01b\x87Rq\x1e(K\x01K\x02\x85h\x08\x89U\x10\xad8\x9c9\x10\xb5\xee\xbf\xffa\xa2hWR\xcf?tbu}q\x1f(h\x03G@\t\xba\xbc\xb8\xad\xc8\x14h\x04G?\xd9\x99%]\xadV\x00h\x05h\x06h\x08U\x08\xe3X\xa9=\xc1\xb1\xeb?\x86Rq h\r\nh\x06h\x08U\x08\x88\xf7\xb9\xc1\t\xd6\xff?\x86Rq!h\x0ch\x06h\x08U\x08v\x7f\xeb\x11\xea5\r@\x86Rq"h\x0eh\x0fh\x10K\x00\x85U\x01b\x87Rq#(K\x01K\x02\x85h\x08\x89U\x10\xcd\xd9\x92\x9a\x94=\x06@]C\xaf\xef\xeb\xef\x02@tbh\x12h\x06h\x08U\x08-\x9c&\x185\xfd\xef?\x86Rq$h\x14G@\r\xb8W\xb2`V\xach\x15h\x16h\x17K\x02h\x18h\x06h\x08U\x08\x8e\x87\xd1\xc2
Run Code Online (Sandbox Code Playgroud)
您也可以下载整个文件(22k).
我正在尝试获取Return用于发送文本和Shift + Return插入换行符的典型IM客户端的行为.有没有办法在Python中用最少的努力实现这一点,使用例如readline和raw_input?
使用HTML5地理位置API时,除纬度和经度外,我还得到"以米为单位的位置精度".究竟是什么意思(米不是准确度的单位)?
我认为它应被解读为"概率为p,请求是在返回位置的米范围内" - 如果是,那么什么是p?它是一个标准偏差(p = 0.682?)两个标准偏差(p = 0.956?)
有没有办法欺骗argparse接受任意数字参数,如HEAD(1)?
head -5 test.txt
Run Code Online (Sandbox Code Playgroud)
相当于
head -n 5 test.txt
Run Code Online (Sandbox Code Playgroud)
我目前的方法是使用parse_known_args()然后处理其余部分,但我希望有一些更优雅的东西.
python ×9
argparse ×1
django ×1
geolocation ×1
hash ×1
html5 ×1
input ×1
jinja2 ×1
matplotlib ×1
pickle ×1
plot ×1
readline ×1
setuptools ×1
string ×1