如何为查询集创建视图文件?

时间:2014-06-17 11:39:37

标签: python django

我是django的新手,我做了很多教程,通常我是通过示例学习的。这是我的models.py文件。所以,我制作了一个查询集,但是如何创建一个视图文件?

我需要views.py文件部分用于过滤数据的查询集。但我不知道如何将它放在观点中。

最简单的方法是什么?我需要为它创建一个forms.py文件吗?

那么,也许你知道怎么做?

from django.db import models
import datetime


class PeopleQuerySet(models.query.QuerySet):
    def active(self):
        return self.filter(active=True)

    def get_sex(self, sex):
        return self.filter(sex=sex)

    def get_age(self, year1, year2):
        return self.filter(year__range=(year1, year2))

    def get_city(self, city):
        return self.filter(city=city)

class PeopleManager(models.Manager):

    def get_queryset(self):
        return PeopleQuerySet(self.model, using=self._db)

    def active(self):
        return self.get_queryset().active()

    def get_sex(self, sex):
        return self.get_queryset().get_sex(sex)


    def get_age(self):
        return self.get_queryset.get_age(year1, year2)

    def get_city(self):
        return self.get_queryset().get_city(city)


class People(models.Model):

    SEX_CHOICES = (
    ('M', 'Vyras'),
    ('F', 'Moteris'),
    )

    CITY_CHOICES = (
    ('Kaunas', 'Kaunas'),
    ('Klaipeda', 'Klaipeda'),
    ('Vilnius', 'Vilnius'),
    )


    YEAR_CHOICES = []
    for y in range(16, 100):
        YEAR_CHOICES.append((y, y))


    name = models.CharField(max_length=111)
    sex = models.CharField(max_length=1, choices=SEX_CHOICES)
    year = models.IntegerField(('year'), max_length=4, choices=YEAR_CHOICES, default=16)
    city =  models.CharField(max_length=111, choices=CITY_CHOICES)
    email = models.EmailField()
    phone = models.CharField(max_length=11)
    slug = models.SlugField()
    active = models.BooleanField(default=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)

    objects = PeopleManager()

    def __unicode__(self):
        return self.name

1 个答案:

答案 0 :(得分:0)

我认为你需要这样的事情People.objects.filter(sex='Male')

在此处查看at django docs

而且here也是一个很好的例子,例如:

Blog.objects.filter(entry__headline__contains='Lennon',
    entry__pub_date__year=2008)

并查看此stackoverflow question