Django models, custom functions

后端 未结 3 1258
暖寄归人
暖寄归人 2020-12-13 00:22

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

相关标签:
3条回答
  • 2020-12-13 01:06

    You can use the staticmethod decorator.

    class Article(models.Model):
        title = models.CharField(...)
        isPublished = models.BooleandField()
    
        @staticmethod
        def get_active():
            return Article.objects.filter(isPublished = 1)
    
    0 讨论(0)
  • 2020-12-13 01:08

    As is stated in the docs here, if you need to add custom row-level functionality to your objects, you need to define custom methods on your models. However, if what you are after is custom table-wide functionality (such as getting all Article objects that qualify certain conditions), you have to define custom methods on model Managers (much as aciniglio above points out in their answer).

    0 讨论(0)
  • 2020-12-13 01:27

    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>]
    
    0 讨论(0)
提交回复
热议问题