【问题标题】:Updating django model with highest value in json array更新 json 数组中具有最高值的 django 模型
【发布时间】:2018-04-13 20:03:53
【问题描述】:

我遇到的问题是我想用 json 值更新 Django 模型。问题是json中的一些值是一个包含多个数字的列表。

这是 json 的样子:

json = {'fields': {'resources': [], 'initiative': [8, 21, 22]}, 'pk': 81}
{'fields': {'resources': [], 'initiative': [5, 8, 22]}, 'pk': 82}
{'fields': {'resources': [], 'initiative': [8, 22]}, 'pk': 83}
{'fields': {'resources': [], 'initiative': [6]}, 'pk': 84}

def update_model():
    for row in json:
Model.objects.filter(id=row['pk']).update(initiative_id=row['fields']['initiative'][0], resources_id=row['fields']['resources'][0])

我不知道如何让模型行在堆栈上正确间隔。

无论如何,当我运行它时,我得到“IndexError:list index out of range”大概是因为此方法只能处理具有 1 个值的列表。

我需要数组中的最高值来获取更新模型的资源和计划。

型号:

class Model(models.Model):
    name = models.CharField(max_length=100, unique=True)
    genre = models.ManyToManyField(Genre, blank=False)
    platform = models.ManyToManyField(Platform, blank=True)
    standard_type = models.ForeignKey(StandardType, default=SetDefaults.set_standard_type_default, blank=True)
    owner = models.ManyToManyField(Owner, blank=True)
    evaluated_by = models.ForeignKey(Evaluator, blank=True, default=SetDefaults.set_default_evaluator())
    business_driver= models.ManyToManyField(BusinessDriver, blank=True)
    initiative = models.ForeignKey(Initiative, null=True, blank=True)
    solution = models.ManyToManyField(Solution, blank=True)
    point_of_contact = models.ForeignKey(Contact, null=True, default=SetDefaults.set_default_contact, blank=True)
    description = models.TextField(blank=True)
    required_by = models.ForeignKey(LifecycleStage, null=False, default=SetDefaults.set_required_by_default, blank=True)
    resources = models.ForeignKey(Resource, null=True, blank=True)
    change_notes = models.TextField(null=True, blank=True)
    change_date = models.DateField(null=True, blank=True)
    is_active = models.BooleanField(default=True)

【问题讨论】:

    标签: python json django list


    【解决方案1】:

    假设您只想分配倡议或资源列表中的第一个值(如果存在):

    def update_model():
        for row in json:
            initiative = row['fields']['initiative']
            resources = row['fields']['resources']
    
            initiative_id = max(initiative) if initiative else None
            resources_id = max(resources) if resources else None
    
            Model.objects.filter(id=row['pk']).update(
                initiative_id=initiative_id, 
                resources_id=resources_id
            )
    

    【讨论】:

    • 嗨伊万。根据我设置问题的方式,我可以理解为什么您会假设我只想要第一个值。我确实想要数组中的所有值,这是我对这个问题感到沮丧的根源。你知道怎么把它们都放进去吗?
    • 我已经更新了。我是 Stack 的新用户,我不知道如何在此处正确地分隔代码,但我希望它有意义。
    • 如果ForeignKey 接受一个值,您打算如何将所有值保存在数组中?您可能需要ManyToManyField 来获取资源和倡议?
    • 你说得对,老实说,我完全忘记了 ForeignKey 只接受一个值。在这一点上,我想要的是取数组中的最大值。我已经编辑了问题以反映这一点。
    猜你喜欢
    • 1970-01-01
    • 2017-06-03
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 2013-12-20
    • 2020-04-30
    • 2013-09-28
    相关资源
    最近更新 更多