gpt4 book ai didi

django - 如何从 Django View 中的模型访问数据?

转载 作者:行者123 更新时间:2023-12-04 04:29:11 24 4
gpt4 key购买 nike

所以我有一个模型文件:

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';

和一个 View 文件 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 View 文件中 first_50_clubs 中的前 50 个俱乐部?

最佳答案

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

Use a subset of Python’s array-slicing syntax to limit your QuerySet to a certain number of results. This is the equivalent of SQL’s LIMIT and OFFSET clauses.


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

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

此外,您不需要在 python 中的代码行末尾放置分号。

希望有帮助。

关于django - 如何从 Django View 中的模型访问数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22395570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com