簡體   English   中英

如何在views.py 中從我的數據庫中獲取內容? [姜戈]

[英]How to get the content from my database in views.py? [Django]

我正在嘗試從我的數據庫中打印content字段,這是我的models.py文件:

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    read_time = models.TimeField(null=True, blank=True)
    view_count = models.IntegerField(default=0)

這是我的views.py文件:-

class PostDetailView(DetailView):
    model = Post
    def get_object(self):
        obj = super().get_object()
        obj.view_count += 1
        obj.save()
        return obj
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        all_texts = {
            'texts': context.content
        }
        print(all_texts[texts])
        return context

我試圖從我的數據庫中訪問content字段中的所有數據,但上述方法不起作用,有什么方法可以訪問content字段中的所有數據,因為我必須對這些字段執行一些操作,就像根據內容的長度計算任何內容的read_time一樣。

只需查詢所有對象並循環查詢集以根據您的需要操作它們,如下所示:

def your_view(self, **kwargs):

    # Get all table entries of Model Post
    queryset = Post.objects.all()

    # Loop each object in the queryset
    for object in queryset:

    # Do some logic
        print(object.content)

    [...]
    return (..., ...)

不必重寫.get_queryset(…)方法[Django的DOC]為,由於對象已經傳遞到環境。 您可以簡單地在模板中渲染它:

{{ object.content }}

如果您在上下文中確實需要這個,您可以將其實現為:

class PostDetailView(DetailView):
    model = Post
    
    # …
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update(
            texts=self.object.content
        )
        return context

如果您需要所有帖子對象,您可以將這些添加到上下文中:

class PostDetailView(DetailView):
    model = Post
    
    # …
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update(
            texts=self.object.content,
            posts=Post.objects.all()
        )
        return context

並將這些渲染為:

{% for post in posts %}
    {{ post.content }}
{% endfor %}

在增加視圖計數器以避免競爭條件時,最好使用F表達式 [Django-doc]

class PostDetailView(DetailView): model = Post def get_object(self): obj = super().get_object() views = obj.view_count obj.view_count = F('view_count') + 1 obj.save() obj.view_count =視圖+1返回對象

首批進口車型

from . models import Post

然后在你的函數中

data=Post.objects.values('content').all()

現在數據具有內容字段中的所有值 data=[{'content':first_value},{'content':second_value},..like this...]

暫無
暫無

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

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