Django模型,自定义功能 [英] Django models, custom functions
本文介绍了Django模型,自定义功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果模型看起来像这样(简化的)
class Article(models.Model):
title = models.CharField(...)
isPublished = models.BooleandField()
def get_active(self):
return Article.objects.filter(isPublicshed = 1)
但是这样做不行
你可以建议一种实现这个功能的方法吗?
解决方案
你可能想要的是一个自定义管理器
从django文档:
#一个称为对象的自定义管理器的示例。
class PersonManager(models.Manager):
def get_fun_people(self):
return self.filter(fun = True)
class Person
first_name = models.CharField(max_length = 30)
last_name = models.CharField(max_length = 30)
fun = models.BooleanField()
objects = PersonManager()
def __unicode __(self):
return u%s%s%(self.first_name,self.last_name)
,然后允许您执行以下操作:
>>> p1 = Person(first_name ='Bugs',last_name ='Bunny',fun = True)
>>> p1.save()
>>> p2 = Person(first_name ='Droopy',last_name ='Dog',fun = False)
>>> p2.save()
>>> Person.objects.get_fun_people()
[< Person:Bugs Bunny>]
I am creating simple application with django. Also, I realized that I am doing some kind of operations very often. For example I often need to get all Article objects which have isPublick = True. So I am thinking is that possible to define get_published function in model?
if models looks like this (simplified)
class Article(models.Model):
title = models.CharField(...)
isPublished = models.BooleandField()
def get_active(self):
return Article.objects.filter(isPublicshed = 1)
But it doesn't work this way
Can you suggest a way of implementing the function?
解决方案
What you probably want is a custom manager
From the django docs:
# An example of a custom manager called "objects".
class PersonManager(models.Manager):
def get_fun_people(self):
return self.filter(fun=True)
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
fun = models.BooleanField()
objects = PersonManager()
def __unicode__(self):
return u"%s %s" % (self.first_name, self.last_name)
which then allows you to do something like:
>>> p1 = Person(first_name='Bugs', last_name='Bunny', fun=True)
>>> p1.save()
>>> p2 = Person(first_name='Droopy', last_name='Dog', fun=False)
>>> p2.save()
>>> Person.objects.get_fun_people()
[<Person: Bugs Bunny>]
这篇关于Django模型,自定义功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文