Super1337
Super1337

Reputation: 226

Django admin limit model from foreign key

I have the following model setup:

The problem is that when I try to pull the object up in the admin page, computer_names links to several hundred thousand rows that aren't relevant and the page never loads. How can I filter computer_names to only the user selected objects for the ManyToMany field?

class ScoringException(models.Model):
    class Meta:
        ordering = ['date_modified']
    requester = models.CharField('Requester',max_length=50,null=False,blank=False)
    computer_names = models.ManyToManyField(Computer)
    domain = models.ForeignKey(Domain)
    exception_kpi_types = models.ManyToManyField(ScoringType)
    expiration_date = models.DateField('Expiration Date')
    reason = models.CharField('Reason',max_length=1000,null=False,blank=False)
    approved = models.BooleanField('Approved')
    date_modified = models.DateTimeField('Date Updated',auto_now=True)

Upvotes: 3

Views: 345

Answers (1)

Derek Kwok
Derek Kwok

Reputation: 13078

You can use raw_id_fields in the admin so that Django doesn't render the hundred thousand rows of data:

@admin.register(ScoringException)
class ScoringExceptionAdmin(admin.ModelAdmin):
    ....
    raw_id_fields = ['computer_names']

With raw_id_fields, Django will display the list of ids for selected m2m objects. A search button is also added to make adding new objects for the m2m relationship easier.

See the documentation for more information.

Upvotes: 1

Related Questions