簡體   English   中英

如何保存從QuerySet返回的隨機項目。 Django,Python

[英]How to save a random item returned from QuerySet. Django, Python

我正在嘗試保存QuerySet中返回的項目,以便稍后它將在下一個模板中顯示所有已保存的項目。 但是我不知道該怎么辦?

1.)如何將“快照”正確發送到數據庫?

我的models.py

class City(models.Model):
    name = models.CharField(max_length=100)

class User(models.Model):
    name = models.CharField(max_length=100)
    city = models.ForeignKey(City, on_delete=models.CASCADE)

class UserDecision(models.Model):
    decision = models.BooleanField(default=False)
    relation = models.ManyToManyField(User)

我的views.py

from django.shortcuts import render
from .models import User
from .forms import UserDecisionForm

def random_views(request):
    shot = User.objects.all().order_by('?')[:1]

    #Begining form here
    if request.method == "POST":
        form = UserDecisionForm(request.POST)
        if form.is_valid():
            decision = form.save(commit=False)
            decision.relation = shot #<--- how to pass this element to the database automatically. According to the result returned from the QuerySet query.
            decision.save()
    else:
        form = UserDecisionForm()

    # other elements
    context = {'shot': shot, 'form':form }
    return render(request, 'index.html', context)

forms.py

from django import forms

from .models import UserDecision

class UserDecisionForm(forms.ModelForm):
    class Meta:
        model = UserDecision
        fields = ('decision',)

UPDATE

簡短版:嘗試decision.relation = [shot]

長版:
decision.relation將返回相關的經理實例 一個類似於<model>.objects返回的管理器,除了它管理與實例decision相關的所有記錄外。
需要說明的是decision.relation實際上是一個數據描述符 ,一個對象(這里的特殊屬性decision ),允許一些巧妙的小把戲在訪問( __get__ )或改變( __set__ )的屬性:
訪問屬性relation ,將通過描述符的__get__方法為您提供上述管理器實例。

設置屬性時(使用__set__ decision.relation = some_variable ),描述符使用其__set__方法,如下所示:

# django.db.models.fields.related_descriptors.py: 518
def __set__(self, instance, value):
    """
    Set the related objects through the reverse relation.

    With the example above, when setting ``parent.children = children``:

    - ``self`` is the descriptor managing the ``children`` attribute
    - ``instance`` is the ``parent`` instance
    - ``value`` is the ``children`` sequence on the right of the equal sign
    """
    ...
    manager = self.__get__(instance)
    manager.set(value)

因此,當您編寫__set__ decision.relation = shot從而調用上面的__set__方法時,描述符將為該關系創建正確的管理器,然后在其上調用set(shot)
最后, set()期望模型實例具有可迭代性,但是您只給了它一個模型實例。


我不確定這是否會真正回答您的問題,但是我不想在開篇文章中添加冗長的注釋,並且在解釋代碼時答案更加清晰。

values()將返回查詢中對象的字典表示形式的查詢集。 您可以使用這些詞典為這些對象制作相同的副本。

user_data = User.objects.order_by('?').values()[:1][0]
user_data[User._meta.pk.name] = None # We cannot use an existing pk for the copy
copied_user = User.objects.create(**user_data)
return render(request, 'index.html', {'shot':copied_user})

在下一個視圖中,您不清楚這些副本正在做什么。 如果您只想顯示一個復制的對象,以避免任何人實際對原始對象進行更改,然后在離開視圖后又再次丟棄這些副本(以免最終得到一個充滿副本的表),則最好更改模板/使用簡單形式僅首先顯示原始數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM