My Django Model has a datetime field named 'updatedOn', I need to use a library function on this model to calculate some statistics, but the function assumes the datetime field name to be 'time', here is how the function uses the datetime:
c = qset.filter(time__year=tt.year, time__month=tt.month, time__day=tt.day).count();
Without touching the library code, how can I create an alias 'time' to refer to 'updatedOn' field, so that I can use the function?
Naming Your Models The model definition is a class, so always use CapWords convention (no underscores). E.g. User , Permission , ContentType , etc. For the model's attributes use snake_case. E.g. first_name , last_name , etc.
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.
def __str__( self ): return "something" This will display the objects as something always in the admin interface. Most of the time we name the display name which one could understand using self object. For example return self.
According to django documentation, you should create a custom user model whenver you start a django project. Because then you will have full control over the fields of the user objects in django, and you can add as many custom fields to the user model as you need and whenever you need.
This old Django Snippet, worked for me, until Django 1.11. As @Jaberwocky commented virtual_only
gets removed in Django 2.0
However, the deprecation warning reads that this field is deprecated in favor of private_only
, although this is not mentioned in the features removed of the above link.
class AliasField(models.Field):
# def contribute_to_class(self, cls, name, virtual_only=False):
# '''
# virtual_only is deprecated in favor of private_only
# '''
# super(AliasField, self).contribute_to_class(cls, name, virtual_only=True)
# setattr(cls, name, self)
def contribute_to_class(self, cls, name, private_only=False):
'''
virtual_only is deprecated in favor of private_only
'''
super(AliasField, self).contribute_to_class(cls, name, private_only=True)
setattr(cls, name, self)
def __get__(self, instance, instance_type=None):
return getattr(instance, self.db_column)
class Order(models.Model):
"""
The main order model
"""
number = AliasField(db_column='id')
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