Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Before save model check some field

Tags:

django

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?

like image 832
Dvex Avatar asked May 17 '16 05:05

Dvex


1 Answers

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)
like image 171
Sergey Gornostaev Avatar answered Oct 02 '22 15:10

Sergey Gornostaev