Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to add a db_index to this Django model?

Tags:

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?

like image 510
TIMEX Avatar asked Jan 29 '11 10:01

TIMEX


People also ask

Does Django create indexes automatically?

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.

What is DB index true in Django?

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).

How does Django implement indexing?

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).

How do I add a model field in Django?

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.


1 Answers

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 
like image 180
Sam Dolan Avatar answered Sep 24 '22 13:09

Sam Dolan