1

Consider I have the below simple model:

class Dimdate(models.Model):
  id = models.AutoField(db_column='Id', primary_key=True)  # Field name made lowercase.
  date = models.DateField(db_column='date')  # Field name made lowercase.

This table is used by many others models (so Dimdate.id is the FK) as below:

class MyModel(models.Model):
  id = models.AutoField(db_column='Id', primary_key=True)  # Field name made lowercase.
  dateid = models.ForeignKey(Dimdate, models.DO_NOTHING, db_column='DateId', blank=True, null=True)  # Field name made lowercase.
  # ...

My problem is that DimDate table contains too many records. When using Django admin UI to add a new MyModel instance, the dropdown menu is showing all of my DimDate which makes it not user friendly.

I did a quick google search but found nothing to restrict the number of DimDate elements retrieved and displayed in the dropdown menu (when adding a MyModel instance). Can I filter my dimdate to include only the dates from 1 month in the past to 1 month in the future?

Eg: If we are the 27th of Jan 2020. Dates range is: [27/12/2019, 27/02/2020]

I am currently using the admin "classic" approach of django (no custom form):

@admin.register(models.MyModel)
class MyModelAdmin(admin.ModelAdmin):

I suspect I will need to override the MyModel form. But even by doing it. How can I limit the number of retrieved DimDate inside my form?

Is there an easier way of doing (as I am new with Django...)?

In case it is needed, I am using Django 2.2.6

1 Answer 1

3

use raw_id_fields in your admin config to prevent loading all objects

@admin.register(models.MyModel)
class MyModelAdmin(admin.ModelAdmin):
    raw_id_fields = ('dateid',)`

it shows up like bellow and you can select object when clicking on it on new window enter image description here

and if you want just filter dropdown items you can add limit_choices_to to you foreignkey field like bellow:

def limit_dim_date_choices():
    return {'date__range': (date(2019,12,27), date(2020,2,27))}

class MyModel(models.Model):
  id = models.AutoField(db_column='Id', primary_key=True)  # Field name made lowercase.
  dateid = models.ForeignKey(Dimdate, limit_choices_to=limit_dim_date_choices, models.DO_NOTHING, db_column='DateId', blank=True, null=True)  # Field name made lowercase.
  # ...
1
  • Using the limit_choices_to works perfectly fine. Thank you !
    – WilliamW
    Commented Jan 28, 2020 at 8:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.