【问题标题】:How to access data from models in view in Django?如何从 Django 视图中的模型访问数据?
【发布时间】:2014-04-19 04:30:15
【问题描述】:

所以我有一个模型文件:

import datetime

from django.db import models

class Organization(models.Model):
    name           = models.CharField(max_length=128, unique=True);
    description    = models.TextField(blank=True);
    location       = models.CharField(max_length=256, blank=True);
    contact_email  = models.EmailField(max_length=128, unique=True);
    org_type       = models.ForeignKey('OrganizationType');
    created_at     = models.DateTimeField(editable=False);
    updated_at     = models.DateTimeField();

def save(self, *args, **kwargs):
    ''' On save, update timestamps '''
    datetime_now = datetime.datetime.now();

    # If there's no ID, it's new
    if not self.id:
        self.created_at = datetime_now;

    # Always update the modified at value
    self.modified_at = datetime_now;

    return super(User, self).save(*args, **kwargs);

class Meta:
    app_label = 'bc';

还有一个视图文件Organization.py:

from django.shortcuts import render, redirect
from django.contrib import auth
from django.core.context_processors import csrf

from BearClubs.bc.forms.user import UserSignUpForm
from BearClubs.bc.models.organization import Organization

def directory(request):
    first_50_clubs = [];

    # get 50 clubs here

return render(request, 'directory.html' {'clubs': first_50_clubs});

我对 Django 很陌生,所以请原谅我。如何获取 Organization.py 视图文件中 first_50_clubs 中的前 50 个俱乐部?

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

    根据documentation,你可以只使用列表切片:

    使用 Python 的数组切片语法的子集来限制您的 QuerySet 到一定数量的结果。这相当于 SQL 的 LIMIT 和 OFFSET 子句。

    def directory(request):
        first_50_clubs = Organization.objects.all()[:50]
    
        return render(request, 'directory.html' {'clubs': first_50_clubs})
    

    另外,你不需要在 python 代码行的末尾添加分号。

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      您可以通过以下查询在 first_50_clubs 中获得前 50 个俱乐部

      first_50_clubs = Organization.objects.all().order_by('id')[:50]
      

      它会在插入时获取记录。

      如果您想要 last insert 50 记录,那么只需在 order_by 中使用 - 。喜欢:

      first_50_clubs = Organization.objects.all().order_by('-id')[:50]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 2021-09-24
        • 1970-01-01
        • 2020-06-06
        • 2016-08-11
        相关资源
        最近更新 更多