简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM