HBMCS
HBMCS

Reputation: 776

Check if record with multiple fileds exists in database before saving the form

I have this model:

class Venue(models.Model):
    venue_name = models.CharField(max_length=50)
    venue_city = models.CharField(max_length=50)

and I have a form where users input the venue name and city. I'd like to check if a record already exists in the database, with both fields already taken in the same record. There could be the same venue name in different cities for example.

I've added a check in my forms.py:

class VenueForm(forms.ModelForm):
    class Meta:
        model = Venue
        fields = ['venue_name', 'venue_city', 'venue_country']

    def save(self, commit=True):
            venue = super(VenueForm, self).save(commit=False)
            venue_name = self.cleaned_data['venue_name']
            venue_city = self.cleaned_data['venue_city']
            if Venue.objects.filter(venue_city=self.cleaned_data['venue_city']).exists() and Venue.objects.filter(venue_name=self.cleaned_data['venue_name']).exists(): # I know this doesn't work: it's as far as I can get.
                logger.error(venue_name + ' already exists')
            if commit:
                venue.save()

            return venue

and, finally, my view.py:

def venue_add_view(request):

    form_venue = VenueForm(request.POST or None)

    if form_venue.is_valid():

        form_venue.save()

    context = {
        'form_venue': form_venue,
    }

    return render(request, "venue-add.html", context)

As it is now it successfully checks if name or city already exist. What I want to do is ask the database if they exist in the same record. How can I do that?

Upvotes: 0

Views: 1162

Answers (1)

bb4L
bb4L

Reputation: 919

You can simply add both statements into the same filter:

Venue.objects.filter(venue_city=self.cleaned_data['venue_city'], venue_name=self.cleaned_data['venue_name']).exists()

This checks if a Venue object with the city and the name of the cleaned_data exists.

Upvotes: 1

Related Questions