2014-03-14 55 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] 
相關問題