Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model using reserve Python keyword for DB columns name

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 ?

like image 880
Dimag Kharab Avatar asked Apr 06 '15 06:04

Dimag Kharab


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.

How can create primary key in Django 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.

What is AutoField in Django?

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.

How is Django DB models used to define data models for a Django project?

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.


Video Answer


1 Answers

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.

like image 63
Ankit Popli Avatar answered Nov 02 '22 22:11

Ankit Popli