Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models, custom functions

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?

like image 516
Oleg Tarasenko Avatar asked Sep 03 '09 07:09

Oleg Tarasenko


People also ask

What is custom model in Django?

Django comes with an excellent built-in User model and authentication support. It is a primary reason most developers prefer Django over the Flask, FastAPI, AIOHttp, and many other frameworks.

How do I add a field to a Django model?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

What is Django coalesce?

Coalesce. Accepts a list of at least two field names or expressions and returns the first non-null value (note that an empty string is not considered a null value). Each argument must be of a similar type, so mixing text and numbers will result in a database error.

What is the @property in Django?

The @property decorator is internally taking the bounded method as an argument and returns a descriptor object. That descriptor object then gets the same name of the old method therefore the setter method is bound to that method i.e. @radius. setter the method getter is referring too.


1 Answers

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>] 
like image 161
aciniglio Avatar answered Sep 19 '22 07:09

aciniglio