use*_*983 6 django django-models django-views
所以我有一个模型文件:
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';
Run Code Online (Sandbox Code Playgroud)
还有一个视图文件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});
Run Code Online (Sandbox Code Playgroud)
我真的是Django的新手,请原谅。如何在Organization.py视图文件的first_50_clubs中获得前50个俱乐部?
根据文档,您可以只使用列表切片:
使用 Python 的数组切片语法的子集将您的 QuerySet 限制为一定数量的结果。这相当于 SQL 的 LIMIT 和 OFFSET 子句。
def directory(request):
first_50_clubs = Organization.objects.all()[:50]
return render(request, 'directory.html' {'clubs': first_50_clubs})
Run Code Online (Sandbox Code Playgroud)
此外,您不需要在 python 中的代码行末尾放置分号。
希望有帮助。
| 归档时间: |
|
| 查看次数: |
15377 次 |
| 最近记录: |