我有一个模拟最多有 30 个车站的火车线路的模型,因此该模型有 30 个可为空的字段。
模型.py
class TempLine(models.Model):
picking_mode = models.IntegerField(default=1)
start_station = models.CharField(max_length=2000)
end_station = models.CharField(max_length=2000, null=True)
station_1 = models.CharField(max_length=2000, null=True)
station_2 = models.CharField(max_length=2000, null=True)
station_3 = models.CharField(max_length=2000, null=True)
station_4 = models.CharField(max_length=2000, null=True)
station_5 = models.CharField(max_length=2000, null=True)
station_6 = models.CharField(max_length=2000, null=True)
station_7 = models.CharField(max_length=2000, null=True)
station_8 = models.CharField(max_length=2000, null=True)
station_9 = models.CharField(max_length=2000, null=True)
station_10 = models.CharField(max_length=2000, null=True)
station_11 = models.CharField(max_length=2000, null=True)
station_12 = models.CharField(max_length=2000, null=True)
station_13 = models.CharField(max_length=2000, null=True)
station_14 = models.CharField(max_length=2000, null=True)
station_15 = models.CharField(max_length=2000, null=True)
station_16 = models.CharField(max_length=2000, null=True)
station_17 = models.CharField(max_length=2000, null=True)
station_18 = models.CharField(max_length=2000, null=True)
station_19 = models.CharField(max_length=2000, null=True)
station_21 = models.CharField(max_length=2000, null=True)
station_22 = models.CharField(max_length=2000, null=True)
station_23 = models.CharField(max_length=2000, null=True)
station_24 = models.CharField(max_length=2000, null=True)
station_25 = models.CharField(max_length=2000, null=True)
station_26 = models.CharField(max_length=2000, null=True)
station_27 = models.CharField(max_length=2000, null=True)
station_28 = models.CharField(max_length=2000, null=True)
station_29 = models.CharField(max_length=2000, null=True)
station_30 = models.CharField(max_length=2000, null=True)
数据正在使用ajax请求一个一个添加。
所以我必须遍历从 station_1
开始的所有字段..检查是否没有,添加..如果不是..就去下一个。
我是这样尝试的:
def adding_inline_stations(request):
in_line_station = request.GET.get('inLine_stations', None)
obj = TempLine.objects.filter()[0]
for f in obj._meta.get_fields[3:]:
if f is None:
f = in_line_station
f.save()
else:
pass
返回错误 TypeError: 'method' object is not subscriptable
最佳答案
你应该制作一个车站模型。虽然目前您只需要车站的名称,但很快就会变成需要位置、营业时间等。
一旦你制作了这样一个模型(即使它当时只有一个带有名称的字段),与你的行建立多对多关系并以与任何其他相关模型字段相同的方式访问它们.
作为一般的编程规则,如果您将变量命名为 variable_n
,那么是时候重新考虑是否需要将这些对象存储在某种集合中
关于python - 如何迭代 Django 模型字段,并根据条件添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58649234/