社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

如何遍历django模型字段,并根据条件添加值

Ahmed Wagdi • 5 年前 • 1706 次点击  

我有一个模型,它模拟了一条多达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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48339
 
1706 次点击  
文章 [ 2 ]  |  最新文章 5 年前