如何在Django中使用字典来更新模型表

时间:2019-05-13 18:28:54

标签: django database dictionary model save

我似乎无法使用字典更新Django中的Results表,可能是我需要包括用户名作为键,但是我不知道该怎么做?

在func.py

from django.contrib.auth import authenticate
from django.contrib import messages
from django.views.decorators.csrf import csrf_protect
from .forms import SignUp
from .models import Table, Results
from django.contrib.auth.models import User
from .serializers import TableSerializer, SessionAvgSerializer, ResultsSerializer

curArr=[GBP,EUR]

def calc(curArr, user_results, username):
        results = {}
        specs = {'GBP': 1,'USD': 2, 'EUR': 3}
        for item in curArr:
                if item in specs:
                        results[item] = specs[item]
                for (key, value) in results.items():
                        setattr(Results, key, value)
                        Results.save()
        return(results)

在models.py

class Results(models.Model):
    Currency = models.CharField(max_length=32)
    Value = models.IntegerField()
    Units = models.CharField(max_length=4)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

要查看“结果”表的更新:

Username | Currency | Value | Units|

           GBP         1
           EUR         3

但是我得到了这个: Results.save() TypeError:save()缺少1个必需的位置参数:'self'

1 个答案:

答案 0 :(得分:1)

我仍然不确定您要在这里做什么,例如,我不知道usernameuser_results参数的作用-但基本思想很简单:

for currency, value in results.items():
    result = Results.objects.get(Currency=currency)
    result.Value = value
    result.save()

或者您可以提高效率:

for currency, value in results.items():
    Results.objects.filter(Currency=currency).update(Value=value)

无需致电save()的地方。

修改

现在,您已澄清要创建新的结果。所以:

user = User.objects.get(username=username)
for currency, value in results.items():
    Results.objects.create(Currency=currency, Value=value, user=user)