In your views.py
file you would subset your queryset to get the distinct values only. Then you would only return these distinct values to your template.
So, using your example, you have a context object called results
. You don't define how you came to populate that object, or what your model looks like, so lets assume the following model for your application for the sake of argument:
from django.db import models
class MyModel(models.Model):
ip = models.IPAddressField()
Now, lets take a look at views.py
and here we are using Generic Class Based Views:
from django.views.generic.list import ListView
class IpListView(ListView):
def get_queryset(self):
queryset = super(IpListView, self).get_queryset()
unique_ips = queryset.values('ip').distinct()
return unique_ips
Note: You could also put the distinct()
method above directly into the urls.py
queryset object below...
In your urls.py
you would make sure you route IpListView
to your template. Something like:
from django.conf.urls import patterns, url
from myapp.models import MyModel
from myapp.views import IpListView
urlpatterns = patterns('',
url(r'^$',
IpListView.as_view(
queryset=MyModel.objects.order_by('ip'),
context_object_name='results',
template_name='myapp/mytemplate.html',
), name='mymodel-ips'
)
)
Note here how results
is your context object name. This means that all your ip
field values will be available in your template mytemplate.html
as:
for r in results:
ip_option = r.ip
And because you have already subset the queryset to only have the unique IPs, you get what you needed. So you just need to loop through:
<p>Choose:
<select>
{% for item in results %}
<option value="{{ item.ip }}">{{ item.ip }}</option>
{% endfor %}
</select>
<button type="button">Filter</button>
</p>
One caveat here: you don't state if you need any other fields from your model. If you do, the queryset I listed above will modify the results you get, and you might not get back what you expect if you wanted to use other values entered to be returned...