6

I need to check if other models already created, have a field filled . If another model has the field with any value, the current model that attempts to create should not happen. And if possible send an error message.

This is my current code:

class Video(models.Model):
  #####
  # Fields of model
  #####

  def save(self, force_insert=False, force_update=False, *args, **kwargs):
    some_video = Video.objects.all().filter(field_boolean=True).first()
    if not some_video:
      # Save current model
      super(Video, self).save(force_insert, force_update, *args, **kwargs)
    else:
      # avoid save method for the current model created and send error message

What am I doing wrong or what I'm missing? What is the correct way to do this?

2
  • 1
    What is the problem? May 17, 2016 at 6:41
  • @SergeyGornostaev Mi code not work.
    – Dvex
    May 17, 2016 at 14:46

1 Answer 1

11

Firstly, you do not need to use all() and filter() together. Secondly, use exists() instead of first(). It returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible.

class Video(models.Model):
    name = models.CharField(max_length=30)
    field_boolean = models.BooleanField()

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if Video.objects.filter(field_boolean=True).exists():
            print('Video with field_boolean=True exists')
        else:
            super(Video, self).save(*args, **kwargs)
1
  • The method save, also works with method update? The variable self, Is the current row that is to be created?
    – Dvex
    May 17, 2016 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.