I am developing a Django Restful API & I am in a situation where my DB coulmn name ( ie lambda conflicting with reserved python keyword), I need to use this in my model.py
file which has code
CHOICES = (
(1, 'Default'),
(0, 'Not Default'),
)
profileid = models.AutoField(primary_key=True)
alpha = models.FloatField()
beta = models.FloatField()
gamma = models.FloatField()
lambda = models.FloatField() # <---------- How to use lambda for column name
is_default = models.IntegerField(choices=CHOICES)
** I want this without renaming the DB column name
Any suggestion how it can be done ?
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field. If you add your own primary key field, the automatic one will not be added.
According to documentation, An AutoField is an IntegerField that automatically increments according to available IDs. One usually won't need to use this directly because a primary key field will automatically be added to your model if you don't specify otherwise.
The basics: Each model is a Python class that subclasses django.db.models.Model . Each attribute of the model represents a database field. With all of this, Django gives you an automatically-generated database-access API; see Making queries.
You can use Field.db_column
for the same. As per the documentation, it should work:
my_lambda = models.FloatField(db_column='lambda')
The name of the database column to use for this field. If this isn’t given, Django will use the field’s name.
If your database column name is an SQL reserved word, or contains characters that aren’t allowed in Python variable names – notably, the hyphen – that’s OK. Django quotes column and table names behind the scenes.
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