class Comments(models.Model): content = models.ForeignKey(Content)
Do I need to add a db_index to "content"? Or would that automatically be indexed because it's a foreign key?
Django does create indexes automatically for some fields. For example it is stated in the documentation for Foreign Keys: A database index is automatically created on the ForeignKey.
This means look ups using the primary key are optimized. If you do a lot of lookups on a secondary column, consider adding an index to that column to speed things up. Keep in mind, like most problems of scale, these only apply if you have a statistically large number of rows (10,000 is not large).
By default, indexes are created with an ascending order for each column. To define an index with a descending order for a column, add a hyphen before the field's name. For your query, models. Index(fields=['last_name', 'first_name','-date_of_birth',]), would create SQL with (last_name, first_name, date_of_birth DESC).
To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.
Unless specified otherwise, an index will be created for a ForeignKey
. Relevant source code:
class ForeignKey(RelatedField, Field): # snip def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs): # snip if 'db_index' not in kwargs: kwargs['db_index'] = True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With