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'
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
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? 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.
By default, Django adds an id field to each model, which is used as the primary key for that model.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With