从Django视图中在SQLite模型中获取JSON字段值

0 投票
0 回答
21 浏览
提问于 2025-04-12 10:27

我正在尝试从一个模型中获取一个叫 correct_answer 的值,这个模型是从外部API获取的,里面有一个JSON字段。这个值会用在一个条件判断中,用来决定是重定向到正确答案的页面,还是显示一个新问题(如果答案错误的话)。

当我试图从一个模拟的模型中以字典的方式访问这个值时,我的测试报错了,提示 'DefferedAttribute' object is not subscriptable。我们可以说数据没有从外部API获取,但我检查过模拟的模型是可以正常工作的。

这是我的代码:

from django.shortcuts import redirect, render, HttpResponse
from django.template import loader
from .forms import QuestionForm, QuestionLevelForm
from urllib.request import urlopen, URLError
from .models import Log

def process_question(request):
    form={};
    if 'level' in request.POST:
        url = 'http://opentb.com/api.php?amount=1&category=9&difficulty='+request.POST['level']+'&type="multiple"'
        try:
            response = urlopen(url)
        except URLError as e:
            if hasattr(e, 'reason'):
                HttpResponse('Reaching server failed: ', e.reason)
            elif hasattr(e, 'code'):
                HttpResponse('Couldn\'t fufill request', e.code)
        else:
            question = response["results"][0]
            form = QuestionForm(question)
            Log.question = question #How to test this works?
            Log.save(update_fields=['question'])
            return render(request, "log/question.html", {"question": question, "form": form})
    elif 'answer' in request.POST:
        if request.POST["correct_answer"] == Log.question['correct_answer']: #This is the conditional I need 
            return redirect('/log/reward')
        else:
            notification = "Wrong answer"
            level = QuestionLevelForm
            return render(request, "log/question.html", {"form": level, "notification": notification})
    else: 
        form = QuestionLevelForm();

    return render(request, "log/question.html", {"form": form})

这是我的模型:

from django.db import models

class Log(models.Model):
   recipe_ingredients = models.JSONField(null=True)
   recipe_area =  models.JSONField(null=True) 
   recipe_categories = models.JSONField(null=True)
   activities = models.JSONField(null=True)
   question = models.JSONField(default=dict)

class Meta:
    abstract = True

def save(self, *args, **kwargs):
    self.__class__.objects.exclude(id=self.id).delete()
    super(Log, self).save(*args, **kwargs)

@classmethod
def load(cls):
    try:
        return cls.objects.get()
    except cls.DoesNotExist:
        return cls()

经过几次尝试查询这个字段后,我找到了一条在 Stackoverflow上的问题,对我来说更有意义。不过,在这种情况下并没有解决我的问题。

有没有人能指出我遗漏了什么或者做错了什么呢?

0 个回答

暂无回答

撰写回答