Note that there are some explanatory texts on larger screens.

plurals
  1. POFiltering model results for Django admin select box
    text
    copied!<p>I just started playing with Django today and so far am finding it rather difficult to do simple things. What I'm struggling with right now is filtering a list of status types. The StatusTypes model is:</p> <pre><code>class StatusTypes(models.Model): status = models.CharField(max_length=50) type = models.IntegerField() def __unicode__(self): return self.status class Meta: db_table = u'status_types' </code></pre> <p>In one admin page I need all the results where type = 0 and in another I'll need all the results where type = 1 so I can't just limit it from within the model. How would I go about doing this?</p> <p><strong>EDIT:</strong> I should have been a bit more clear. I have a model "Unit" which has a foreign key to to StatusTypes. The models are as follows:</p> <pre><code>class StatusTypes(models.Model): status = models.CharField(max_length=50) type = models.IntegerField() def __unicode__(self): return self.status class Meta: db_table = u'status_types' class Unit(models.Model): name = models.CharField(unique=True, max_length=50) status = models.ForeignKey(StatusTypes, db_column='status') note = models.TextField() date_added = models.DateTimeField() def __unicode__(self): return self.name class Meta: db_table = u'units' </code></pre> <p>So now in the admin page for the unit model I want to limit the status to only those with type = 1. Based off of lazerscience response below I tried the following code:</p> <pre><code>from inv.inventory.models import Unit from django.contrib import admin class UnitAdmin(admin.ModelAdmin): def queryset(self, request): qs = super(UnitAdmin, self).queryset(request) return qs.filter(type=0) admin.site.register(Unit, UnitAdmin) </code></pre> <p>But, it didn't change the select box at all. I also tried printing the value of qs and nothing was outputted to my terminal so I'm wondering if I have to some how call queryset?</p> <p><strong>EDIT 2:</strong> It might not have been clear that I want to filter this for the status dropdown that is on the create page for the Unit model.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload