D
D
Dennis2016-06-01 15:18:40
Django
Dennis, 2016-06-01 15:18:40

Django - how to remove duplicate objects in a view?

models.py

class Location(models.Model):
        name = models.CharField(max_length=100, verbose_name=u"Локация", default=u'')
        country = models.CharField(max_length=100, verbose_name=u"Страна", default=u'')
    
    class Country(models.Model):
        name = models.CharField(max_length=50, verbose_name=u"Страна")
    
    class Photo(models.Model):
        location = models.ForeignKey(Location, null=True, verbose_name=u'Фото')
        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 a list of countries in browse_locations.html without repetition. For example, I add a location object with the US country, then I add another object that also has the US country. But in the view, I do not need to see all the Country objects (which are duplicated), but only one at a time.
Thanks!!!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Андрей Инишев, 2016-06-01
@inish777

Вроде как-то так

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()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question