Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 319
Super1337 Avatar asked Feb 12 '26 10:02

Super1337


1 Answers

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.

like image 74
Derek Kwok Avatar answered Feb 14 '26 23:02

Derek Kwok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!