简体   繁体   中英

How Do I create database Models in Django?

Before heading straight to my issue,I would like to state that I am a newbie in Django. My database models were created in Sqlalchemy Flask. I want to write the same database model in my Django application as well. To keep it simple this is how a model was created using Sqlalchemy in Flask. flask_model.py

class LeadsStatus(db.Model):
    __tablename__ = 'leads_status'
    if leadgenapp.config['TESTING']:
        f_key = 'companies.id'
    else:
        __table_args__ = {'schema': tbl_schema}
        f_key = f'' + tbl_schema + '.companies.id'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    company_id = db.Column(db.Integer, db.ForeignKey(f_key), nullable=False, index=True)
    status = db.Column(db.String(120))
    users_id = db.Column(db.Integer)
    assign_date = db.Column(db.DateTime)

    companies = db.relationship('Companies', backref='leadstatus')

This model contains a foreign key. My issue is while I am creating the same model it throws an error stating that f_key is not defined . This is how I have written the model. django_model.py

class LeadsStatus(models.Model):
    __tablename__ = 'leads_status'
    # if leadgenapp.config['TESTING']:
    #     f_key = 'companies.id'
    # else:
    #     __table_args__ = {'schema': tbl_schema}
    #     f_key = f'' + tbl_schema + '.companies.id'

    id = models.IntegerField(primary_key=True, auto_created=True)
    company_id = models.ForeignKey(f_key, nullable=False, index=True, on_delete=models.CASCADE)
    status = models.CharField(max_length=120)
    users_id = models.IntegerField()
    assign_date = models.DateTimeField()
    companies = models.relationship('Companies', backref='leadstatus')

I understood the reason of the error but what I cannot understand is how to overcome it? I apologize if the question might sound trivial for the reasons but I am just a newbie to django and I not aware of how things are going on in the Django's ORM

TL;DR:

It's limitation of Django. You can't do that easily.


Long Answer

I don't think the Django ORM will flexible enough for doing custom ForeignKey because it try to hind the complexity such as migration script.

For example, In Sqlalchemy itself can not generate migrations automatically, you need to write your own migration files,

But in Django what you need to do is type the command python manage makemigrations then you will got the migration for your database as long as when you change your Model schema.

You just run the same command. Django will know what you have change and create a new migration file for that.

So the sense of ForeignKey . Django need to know what exactly model you have connect to for creating migration file. If you do like a dynamic foriegn key, that might make Django doing or mapping wrong in some model.

What I am gonna suggest is please follow Django Model and ignore about schema and database. Let's Django do it for you and focus on creating your awesome app!

That's my 2 cents.


Read more in this link.

https://docs.djangoproject.com/en/3.1/ref/models/fields/#foreignkey https://docs.djangoproject.com/en/3.1/topics/migrations/

See the documentation of Django's ForeignKey

You should provide it with your model class and not a table name.

So it should be something like:

company_id = models.ForeignKey('Company', on_delete=models.CASCADE)

where 'Company' is another model class.

EDIT: If you really need dynamic foreign key, as Kanisorn Sutham suggests, you may read aboutDjango's contenttypes framework

try this - this should work

        company_id = models.ForeignKey('Company', nullable=False, index=True, on_delete=models.CASCADE)

Basically the first argument is the name of the model. The company_id in this case would map to the primary key (id) of the related table Company.

btw - you can try the Imagine smart compiler to generate clean code for your Django models (as well as APIs) from a very simple config. Amongst other functionality, it generates code in the correct way to model foreign key relationships in Django. You can also try a demo here imagine.ai/demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM