Saturday 18 June 2016

Constraints on models in Django

Okay so I cannot take the risk of being discovered as wrong and hence foolish by someone else or even myself at some later point in time. Hence the following is just what I know till now. I don't have any claims on the truthiness of the following statements.
In Django, while connecting to a database, we write models in the models.py file. 
A model is nothing but a python class that defines a table structure. This definition is then used to convert the models.py file into an actual database populated with as many tables as there are models in the file. 
I am intentionally skipping over the details on how to write models and then apply them to a database. I might come back and edit this post but for now I assume the reader knows this already or have an alternative source to learn it.
What I would like to say is that I found certain constraints in the way which we are allowed to define these models. And these aren't so complicated either. I mean databases are very important part of any application. And one would want their database schema to be absolutely accurate and efficient. Flexibility in designing a database for an application is of paramount importance. You don't want any compromises do you?
But when designing tables through models of Django, there is some limitations on what we are allowed to do with our tables. Some of these restraints are as follows:
1) No composite keys:
Okay so one field isn't always enough to uniquely identify all other fields in a table. Someone should go tell Django that. Apparently you are not allowed have primary key consisting of more than one column in the table.
2)  No table without a primary key:
Okay so this isn’t perhaps a bad thing. All tables should have a primary key. While most of them do, some of them don’t quite need one. But Django does not allow this to be our choice. It will rectify if we forgot to specify the primary key constraint on any of the field. In this case Django will automatically add another field by the name of id and make it the primary key with auto increment feature.
3) Key attributes must have default values:
This isn't so bad either but still the choice should be ours. Yet Django will throw an error if you forget to mention the default value of a key attribute whether it be the primary key or the foreign key.
4) The name of key attributes ends a certain way:
Assume that you have a key field by the name of "abc". Then when you migrate the changes to the database, then you will see that Django has automatically added a "_id" at the back of that field's name. Now this is annoying. I mean what is with Django and the word "id".

No comments:

Post a Comment