首页 \ 问答 \ 在Django中自动分配模型字段值(Automatically assigning model field values in Django)

在Django中自动分配模型字段值(Automatically assigning model field values in Django)

有没有办法在定义模型时自动为Django中的模型设置字段值? 这可以用于存储诸如时间戳之类的东西(例如),但也可以用于创建被构造为其他的某个功能的字段。

换句话说,我正在寻找这样的东西:

class Foo(models.Model):

spam = models.CharField(max_length=2000)
my_other_field = ###?

def generate_my_other_field():
    #Some algorithm to determine the value of my_other_field

Is there a way to automatically set field values for models in Django when defining the model? This could be used for storing something like a timestamp (for example), but also for creating a field which is constructed as some function of the others.

In other words, I'm looking for something like this:

class Foo(models.Model):

spam = models.CharField(max_length=2000)
my_other_field = ###?

def generate_my_other_field():
    #Some algorithm to determine the value of my_other_field

原文:https://stackoverflow.com/questions/6643604
更新时间:2021-09-05 16:09

最满意答案

如果您想一次访问3个字符的字符串,则需要使用切片

您可以使用像这样的列表理解来获得字符串的3个字符长的部分列表:

>>> x = 'this is a string'
>>> step = 3
>>> [x[i:i+step] for i in range(0, len(x), step)]
['thi', 's i', 's a', ' st', 'rin', 'g']
>>> step = 5
>>> [x[i:i+step] for i in range(0, len(x), step)]
['this ', 'is a ', 'strin', 'g']

重要的是:

[x[i:i+step] for i in range(0, len(x), step)]

range(0, len(x), step)我们提供了每个step字符切片开始的索引。 for i in将会遍历这些指数。 x[i:i+step]获得从索引i开始的x的片段,并且是step长字符。

如果你知道每次都会得到四件,那么你可以这样做:

a, b, c, d = [x[i:i+step] for i in range(0, len(x), step)]

如果3 * step < len(x) <= 4 * step则会发生这种情况。

如果你没有完整的四部分,那么Python会给你一个ValueError试图解压这个列表。 因此,我会认为这种技术非常脆弱,不会使用它。

你可以简单地做

x_pieces = [x[i:i+step] for i in range(0, len(x), step)]

现在,您曾经访问a ,您可以访问x_pieces[0] 。 对于b ,可以使用x_pieces[1]等。 这可以让你更灵活。


If you'd like to access a string 3 characters at a time, you're going to need to use slicing.

You can get a list of the 3-character long pieces of the string using a list comprehension like this:

>>> x = 'this is a string'
>>> step = 3
>>> [x[i:i+step] for i in range(0, len(x), step)]
['thi', 's i', 's a', ' st', 'rin', 'g']
>>> step = 5
>>> [x[i:i+step] for i in range(0, len(x), step)]
['this ', 'is a ', 'strin', 'g']

The important bit is:

[x[i:i+step] for i in range(0, len(x), step)]

range(0, len(x), step) gets us the indices of the start of each step-character slice. for i in will iterate over these indices. x[i:i+step] gets the slice of x that starts at the index i and is step characters long.

If you know that you will get exactly four pieces every time, then you can do:

a, b, c, d = [x[i:i+step] for i in range(0, len(x), step)]

This will happen if 3 * step < len(x) <= 4 * step.

If you don't have exactly four pieces, then Python will give you a ValueError trying to unpack this list. Because of this, I would consider this technique very brittle, and would not use it.

You can simply do

x_pieces = [x[i:i+step] for i in range(0, len(x), step)]

Now, where you used to access a, you can access x_pieces[0]. For b, you can use x_pieces[1] and so on. This allows you much more flexibility.

相关问答

更多
  • 如果您想一次访问3个字符的字符串,则需要使用切片 。 您可以使用像这样的列表理解来获得字符串的3个字符长的部分列表: >>> x = 'this is a string' >>> step = 3 >>> [x[i:i+step] for i in range(0, len(x), step)] ['thi', 's i', 's a', ' st', 'rin', 'g'] >>> step = 5 >>> [x[i:i+step] for i in range(0, len(x), step)] ['t ...
  • 两个步骤,例如, package main import ( "fmt" "strings" ) func main() { s := strings.Split("127.0.0.1:5432", ":") ip, port := s[0], s[1] fmt.Println(ip, port) } 输出: 127.0.0.1 5432 一步,例如, package main import ( "fmt" "net" ) func mai ...
  • 你需要使用循环: public static IEnumerable SplitByLength(this string str, int maxLength) { for (int index = 0; index < str.Length; index += maxLength) { yield return str.Substring(index, Math.Min(maxLength, str.Length - index)); } } 替代方案: ...
  • 我解决了它唯一的方法我知道:螺旋perlmagic,并通过命令行来做。 以下脚本适用于矩形和方形图像。 索引将打印到屏幕上。 use warnings; use strict; my $size = '512x512'; my $offset = 512; unless ($ARGV[0]) { die "Missing filename as arg" } unless (-e $ARGV[0]) { die "$ARGV[0] not found.\n" } my ($newfile, undef ...
  • 你确实可以使用linspace我认为你只需要更加小心,确保你只能得到整数并且要小心边界条件。 minValue = 20; maxValue = 80; Chunks = 9; grid = floor(linspace(minValue,maxValue,Chunks)); grid(end) = grid(end)+1; % fixes the end boundary condition for id=1:length(space)-1 [grid(id),grid(id+1)-1] ...
  • 您可以使用做到这一点textwrap在Python模块: s = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies ne ...
  • 假设您的data.frame有一对列数,这里是一个非常短的代码: >lapply(seq(1,length(df),2), function(u) df[u:(u+1)]) [[1]] a b 1 1 1 2 2 2 3 3 3 [[2]] c d 1 4 4 2 5 5 3 6 6 Assuming your data.frame has a pair number of columns here is a very short code: >lapply(seq(1,length(df),2 ...
  • 您可以从命令行完成目标。 有hg commit , hg revert和hg shelve交互式版本,如果需要,它们有低级选项可以一起修补补丁; 您可以将它们与-i (或--interactive )命令行选项一起使用。 这意味着您可以使用hg commit -i和hg commit --amend -i构建hg commit --amend -i 。 如果您安装了evolve扩展,则可以使用hg uncommit再次从hg uncommit中提取更改; 如果没有,你可以使用hg revert -r .~1 ...
  • 如评论中所述,最好用PHP构建CSV。 但是,要回答如何拆分Javascript数组的问题,可以使用窗口容器。 但是,这意味着对象可能没有相同的Javascript限制,或者您链接的帖子不准确。 (我不确定,因为我没有看到也没有测试过这个限制错误。) http://jsfiddle.net/TYwY8/7/