[Django]-Is it possible to use a table in the database when it is NOT a Django model?

1👍

To do so you would need to create a class (not a model), with methods that use raw SQL. You should see more details here on how to do so: https://docs.djangoproject.com/en/1.9/topics/db/sql/#executing-custom-sql-directly

Please note that you will have to manually create the object with the right properties afterwards.

If you wanted to use Django ORM without the models, I don’t think it is possible. You could however create a model that matches your db in a separate app and never create migrations for it to ensure you don’t accidentally modify the DB.

👤Mijamo

3👍

If you want to access an existing table in your database that is not managed by your application, you can still create a class for it, and tell django to ignore it for migrations.

Just create a model and add the fields you need to access and then add a meta class to tell django to leave it alone.

class MyModel(model.Model):

   class Meta:
      managed = False

you can read about that at https://docs.djangoproject.com/en/1.9/ref/models/options/#managed

0👍

Short answer is, “not really”. Django QuerySet deals with model instances, so everything in QuerySet API is tied into models. Everything expects to return model instances, uses model fields etc.

That said, you should be able to create a model for an existing table. You will need to add db_table to the Meta, so Django knows where the table lives. If you have some indexing, you will need to make sure Django’s idea of indexes is the same as the one in the database. indexed=True on fields and unique_together in Meta should help a lot with that.

Leave a comment