2014-03-14 24 views
3

所以我有一个模型文件:如何在Django中查看模型中的数据?

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个俱乐部?

回答

1

按照documentation,你可以使用列表切片:

使用Python的数组切片语法的一个子集,以您的查询集 限制一定数量的结果。这相当于SQL的LIMIT 和OFFSET子句。

def directory(request): 
    first_50_clubs = Organization.objects.all()[:50] 

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

而且,你不必把分号在在Python代码行的末尾。

希望有所帮助。

1

您可以通过下面的查询得到前50名的俱乐部中first_50_clubs

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

它得到了插入时,会提取记录。

如果你想最后插入50记录,然后只使用-order_by。如:

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