Django — how to remove duplicate objects in the view?

models.py

class Location(models.Model):
 name = models.CharField(max_length=100, verbose_name=u"Location", default=u")
 country = models.CharField(max_length=100, verbose_name=u"Country", default=u")

 class Country(models.Model):
 name = models.CharField(max_length=50, verbose_name=u"Country")

 class Photo(models.Model):
 location = models.ForeignKey(Location, null=True, verbose_name=u Photos')
 photo = models.ImageField(upload_to='photos', null=True)


forms.py

class LocationForm(forms.ModelForm):

 class Meta:
 model = Location
 fields = ['name', 'country']


 photos = MultiFileField(min_num=1, max_num=10)

 def save(self, commit=True):
 instance = super(LocationForm, self).save(commit)
 for each in self.cleaned_data['photos']:
 Photo.objects.create(photo=each, location=instance)

 return instance

views.py

class AddLocationPageView(CreateView):
 model = Location
 form_class = LocationForm
 template_name = 'add_location.html'

 class BrowseLocationsPageView(ListView):
 model = Country
 context_object_name = 'countries'
 template_name = "browse_locations.html"


add_location.html

<form action method="POST">{% csrf_token %}
 {{ form|crispy }}
 <button class="btn btn-default" type="submit">Add</button>
 </form>


browse_locations.html

{% for country in countries %}
 {{ country }}
 {% endfor %}


I need to get in browse_locations.html list of countries without repeating. For example, I added the feature locations with the country USA, then I add another object also country USA. But in the view I need to see not all the Country objects (which are duplicated), but only one at a time.

Thank you!!!
July 9th 19 at 10:03
1 answer
July 9th 19 at 10:05
Like somehow
class BrowseLocationsPageView(ListView):
 model = Country
 context_object_name = 'countries'
 template_name = "browse_locations.html"

 def get_queryset (self):
 return Country.objects.order_by().values('name').distinct()
not... distinct() didn't work... probably because I'm on SQLite - Mackenzie.Pfannersti commented on July 9th 19 at 10:08
actually I'm trying to work around the problem in the view.. but the root of the problem in creating the model Country during object creation Location.. it turns out that I can many times to create the same country... although in fact I don't need... I just need to create a Location or create an object the Country or to bind an existing country (which was created by someone else during the creation of some Locations).. ??? - Mackenzie.Pfannersti commented on July 9th 19 at 10:11
Apparently, that sort of thing:
class Country(models.Model):
 name = models.CharField(max_length=50, verbose_name=u"Country")

 class Meta:
 unique_together = ('name', )
- Letha_Kuhn commented on July 9th 19 at 10:14

Find more questions by tags Django