I have multiple objects saved in my database but I would only like to show items in my queryset that are unique and if they actually have an item saved.
models.py
class Everything(models.Model):
profile = models.ForeignKey(User)
playlist = models.CharField('Playlist', max_length = 2000, null=True, blank=True)
platform = models.CharField('Platform', max_length = 2000, null=True, blank=True)
video = models.CharField('VideoID', max_length = 2000, null=True, blank=True)
def __unicode__(self):
return u'%s %s %s %s' % (self.profile, self.playlist, self.platform, self.video)
views.py
playlist2 = Everything.objects.filter(profile=request.user)
template
<select name ="playlist2">
{% for item in playlist2 %}
<option value="{{item.playlist}}">{{item.playlist}}</option>
{% endfor %}
</select>
There doesn’t have to be a playlist because null=True and blank=True. Some of the items in playlist might also be duplicated. How do I show only the distinct items that have values in them?
You can use
excludeanddistinctqueryset functions (docs).However in your case it is not that simple since your
CharFielddefinitions allow bothNULL(null=True) and empty string (blank=True) values. So that means you have to test for two conditions and for that you have to useQ(docs) objects:That is exactly why Django docs do not recommend to use
null=Truefor string model fields (docs). Here is excerpt:If you follow this conversion, then your filter lookup becomes much simpler: