Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django model instance variables for transient use

Tags:

python

django

I would like to create some instance variables for my model subclass, but when saving the object to the database I don't want a table column for that variable. I read in some places you would do this by overriding init() like how you would create normal instance variables in other classes. Is this the accepted way for subclasses of model? Are there other approaches?

models.py:

class MyModel (models.Model):
    name = models.CharField(max_length=300)

    def __init__(self, *args, **kwargs):
        super(MyModel, self).__init__(*args, **kwargs)
        self.tempvar = ''

views.py:

myModel = MyModel()
myModel.tempvar = 'this will not be saved in the database'
like image 589
prostock Avatar asked May 31 '12 23:05

prostock


People also ask

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What is def __ str __( self in Django?

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.

What is @property in Django models?

What is @property in Django? Here is how I understand it: @property is a decorator for methods in a class that gets the value in the method. But, as I understand it, I can just call the method like normal and it will get it.

Does every Django model have an ID?

By default, Django adds an id field to each model, which is used as the primary key for that model.


1 Answers

That's an acceptable way of doing it, although you don't need to initialize it unless there's a chance you may try to access it when it doesn't exist. Also, consider if you should be using a property instead.

like image 111
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 06:09

Ignacio Vazquez-Abrams