Django Python : Manager isn't accessible via model instances

huangapple go评论72阅读模式
英文:

Django Python : Manager isn't accessible via model instances

问题

我试图查询一个对象集合并使用对象的数量来进行循环,以呈现每个对象的参数。我使用一个二维数组来存储这些参数,以便它们可以与其对象相对应地呈现。我希望不仅提供一个解决方案,还提供一种更好的通用方法。附言:我是django的新手

这是来自views.py的代码:

def flashcard(response):
    form = Flashcard_verif(response.POST)

    if response.method == "POST" and form.is_valid():
          
        head = form.cleaned_data["header"]
        ques = form.cleaned_data["question"]
        ans = form.cleaned_data["answer"]
            
        flashcard_data = Flashcard(header=head, question=ques, answer=ans)

        # 这是错误发生的地方
        flashcard_obj = Flashcard(header=head, question=ques, answer=ans).objects.all()

        rawHeader, rawQuestion, rawAnswer = Flashcard(header=head, question=ques, answer=ans).flash_format()
        
        flashcard_data.save()

        if len(flashcard_lib) > 1:
            for i in range(0, len(flashcard_lib), 1):
                flashcard_lib.append([rawHeader, rawQuestion, rawAnswer])
            
            print(flashcard_lib)
        
            return render(response, "main/Flashcard.html", {
            "form": form,
            "Flashcard_lib": flashcard_lib,
            "flashcard": flashcard_obj})
        else:
            flashcard_lib.append([rawHeader, rawQuestion, rawAnswer])
            print(flashcard_lib)
            
            return render(response, "main/Flashcard.html", {
            "form": form,
            "header": rawHeader, 
            "question": rawQuestion, 
            "answer": rawAnswer
            })
        

    
    else:
        form = Flashcard_verif()
    
    return render(response, "main/Flashcard.html", {
        "form": form})

这是使用二维数组的模板:

<div class="flashcard-view" id="flash" style="visibility: hidden">
    {% if Flashcard_lib|length >= 2 %}
        {% for i in flashcard_obj %}
            <div class="flashcard">
            {{ i.0 }}
            {{ i.1 }}
            {{ i.2 }}
            </div>
        {% endfor %}
    {% else %}
        <div class="flashcard">
        {{ header }}
        {{ question }}
        {{ answer }}
        </div>
    {% endif %}
</div>

当我运行服务器时,我注意到if语句执行了,但for循环没有执行。这有点是一个两全其美的问题,如何让它遍历列表。

英文:

I'm trying to query an object set and use the number of the amount of objects to do a for loop that will present parameters of each object. I'm using a 2D array to store the parameters so they can be presented respective to their object. I would like not just a solution but a better way in general of doing this .p.s. I'm new to django

This is the code from views.py

def flashcard(response):
    form = Flashcard_verif(response.POST)

    if response.method == &quot;POST&quot; and form.is_valid():
          
        head = form.cleaned_data[&quot;header&quot;]
        ques = form.cleaned_data[&quot;question&quot;]
        ans = form.cleaned_data[&quot;answer&quot;]
            
        flashcard_data = Flashcard(header=head, question=ques, answer=ans)


        # this is where the error is occuring
        flashcard_obj = Flashcard(header=head, question=ques, answer=ans).objects.all()

        rawHeader, rawQuestion, rawAnswer = Flashcard(header=head, question=ques, answer=ans).flash_format()
        
        flashcard_data.save()

        if len(flashcard_lib) &gt; 1:
            for i in range(0, len(flashcard_lib), 1):
                flashcard_lib.append([rawHeader, rawQuestion, rawAnswer])
            
            print(flashcard_lib)
        
            return render(response, &quot;main/Flashcard.html&quot;, {
            &quot;form&quot;:form,
            &quot;Flashcard_lib&quot;:flashcard_lib,
            &quot;flashcard&quot;:flashcard_obj})
        else:
            flashcard_lib.append([rawHeader, rawQuestion, rawAnswer])
            print(flashcard_lib)
            
            return render(response, &quot;main/Flashcard.html&quot;, {
            &quot;form&quot;:form,
            &quot;header&quot;:rawHeader, 
            &quot;question&quot;:rawQuestion, 
            &quot;answer&quot;:rawAnswer
            })
        

    
    else:
        form = Flashcard_verif()
    
    return render(response, &quot;main/Flashcard.html&quot;, {
        &quot;form&quot;:form})

This is my template that utilises the 2d array:

&lt;div class=&quot;flashcard-view&quot; id=&quot;flash&quot; style=&quot;visibility: hidden&quot;&gt;
    {% if Flashcard_lib|length &gt;= 2 %}
        {% for i in flashcard_obj %}
            &lt;div class=&quot;flashcard&quot;&gt;
            {{ i.0 }}
            {{ i.1 }}
            {{ i.2 }}
            &lt;/div&gt;
        {% endfor %}
    {% else %}
        &lt;div class=&quot;flashcard&quot;&gt;
        {{ header }}
        {{ question }}
        {{ answer }}
        &lt;/div&gt;
    {% endif %}
&lt;/div&gt;

When i run the server I notice that the if statement executes but the for loop does not. This is kind've a 2 in 1 problem, how do i get it to iterate through the list.

答案1

得分: 0

在以下代码行中:

flashcard_data = Flashcard(header=head, question=ques, answer=ans)

你创建了一个 Flashcard 模型的实例,但没有将其保存到数据库中,要这样做,你需要执行:

flashcard_data.save()

在以下代码行中发生了错误:

flashcard_obj = Flashcard(header=head, question=ques, answer=ans).objects.all()

因为你创建了另一个实例(与上面两行代码中的实例具有相同的数据),然后尝试使用它来获取对象管理器。在 Django 模型实例中,可以表示为:

  • 单个对象(如你的情况)
  • 作为查询集 - 特殊的类似列表的结构,可以为空或包含一个或多个实例。

如果你想获取数据库中的所有 Flashcard 记录,你需要执行:

Flashcard.objects.all()

其中 Flashcard 是你的模型,objects 是对象管理器,它将允许你指定你需要什么:

  • Flashcard.objects.all() - 返回包含所有实例的查询集
  • Flashcard.objects.filter(...) - 返回包含经过筛选的记录的查询集
  • Flashcard.objects.first() - 返回数据库中的第一个对象(而不是查询集!)
    等等。

你不能从实例中调用对象管理器。

英文:

In line

flashcard_data = Flashcard(header=head, question=ques, answer=ans)

You created instance of model Flashcard, but you didnt saved it to db, to do so you need to do:

flashcard_data.save()

An error occured in line

flashcard_obj = Flashcard(header=head, question=ques, answer=ans).objects.all()

because you created another instance (with same data as instance 2 lines above) and then you try to get obj manager with it. In Django model instances can be represented as:

  • single objects (as in your case)
  • As querysets - special list-like structures, empty or containing one or several instances.

If you want to get all Flashcard records in db you need to do

Flashcard.objects.all()

Where Flashcard - is your model, objects - is object manager, that will let you to specify what do you need -
Flashcard.objects.all() - returns queryset with all instases
Flashcard.objects.filter(...) - - returns queryset with filtered records
Flashcard.objects.first() - returns first object (not queryset!) in db
etc..

You cant call obj manager from instance

huangapple
  • 本文由 发表于 2023年7月31日 23:06:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定