Home > OS >  is it possible to add db_index = True to a field that is not unique (django)
is it possible to add db_index = True to a field that is not unique (django)

Time:01-22

I have a model that has some fields like:

current_datetime = models.TimeField(auto_now_add=True)

new_datetime = models.DateTimeField(null=True, db_index=True)

and data would be like :

currun_date_time = 2023-01-22T09:42:00 0330 new_datetime =2023-01-22T09:00:00 0330

currun_date_time = 2023-01-22T09:52:00 0330 new_datetime =2023-01-22T09:00:00 0330

currun_date_time = 2023-01-22T10:02:00 0330 new_datetime =2023-01-22T10:00:00 0330

is it possible new_datetime to have db_index = True ?

the reason i want this index is there are many rows (more than a 200,000 and keep adding every day) and there is a place that user can choose datetime range and see the results(it's a statistical website). i want to send a query with that filtered datetime range so it should be done fast. by the way i am using postgresql

also if you have tips for handling data or sth. like that for such websites i would be glad too hear

thanks.

CodePudding user response:

Yes, It is possible to have datetime field to be true. This could upgrade the performance of queries that sort or screen by the given field.

Other better ways to have an index in datetime field is:

  • To evaluate the query plan and detect any sluggish processes or missing indexes, take advantage of the "explain" command of your database.
  • Employ the "limit" and "offset" parameters within your queries to get only the necessary data.
  • For retrieving associated data in a single query, rather than numerous queries, incorporate the "select_related" and "prefetch_related" methods in your Django queries.
  • To store the outcomes of elaborate queries and dodge running the same query multiple times, make use of caching systems such as Redis or Memcached.
  • Moreover, if there are too many rows and the data is not required for a long period of time, you can contemplate filing the information in another table or database.
  • Related