1

I have a command line script that has sqlalchemy. They look as follows:

class TimestampMixin(object):
    created_date = Column(DateTime, default=func.now())

class DataSource(Base, TimestampMixin):
    """DataSource object"""
    __tablename__ = 'data_source'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    external_location = Column(String)
    games = relationship('Game', backref="data_source")

Now I want to take the same models and put it into a django app. I can do it by hand as follows:

class TimestampMixin(models.Model):
    created_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True

class DataSource(TimestampMixin):
    """DataSource object"""
    name = models.CharField(max_length=255)
    external_location = models.CharField(max_length=255)

    class Meta:
        db_table = 'data_source'

I was wondering if there is a better way. It wouldn't be so bad to start as I only have 9 models, but I would rather not upkeep them. Is there a better(standardized) approach? With djanog I would want to still be able to use things like DjangoRestFramework and DjangoForms. I'm not sure if they work with sqlalchemy.

user
  • 1,220
  • 1
  • 12
  • 31
bink1time
  • 383
  • 1
  • 5
  • 15

1 Answers1

1

Its better to use either Django ORM or SQLAlchemy.

If you want to use SQLAlchemy database in django, what you can do is:

  1. Create a django project.
  2. Update Database settings with desired database's configuration.
  3. Run command: python manage.py inspectdb

This will return the model structure which can be used in Django without changing the database.

You can check it here in detail: https://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb

You can check this SO answer about using SQLAlchemy and Django together.

Community
  • 1
  • 1
ruddra
  • 50,746
  • 7
  • 78
  • 101