Search code examples
djangodjango-modelsdjango-q

NameError while using Q object in a model method


class BlogList(models.Model):
   title = models.CharField(max_length=100)

   def get_first_article_image(self):
      if self.bloglist_articles.exists():
          bloglist = self.bloglist_articles.filter(
                          Q(image_link != '') | Q(image_file != '') ##<---error line
                                               ).order_by('-id')[:1].get()
          if bloglist.image_file:
              return '/'.join([settings.MEDIA_URL, bloglist.image_file.name])
          if bloglist.image_link:
              return bloglist.image_link
      return None

class BlogArticle(models.Model):
   bloglist = models.ForeignKey(BlogList, related_name='bloglist_articles')
   image_file = models.ImageField(upload_to='image/', default='', blank=True)
   image_link = models.CharField(max_length=2000, blank=True)
   image_embed = models.CharField(max_length=2000, blank=True)

if I call in template like

<a href="{{ bloglist_obj.get_first_article_image }}">{{bloglist.title}}</a>

I am getting

NameError at /
global name 'image_link' is not defined

what am I doing wrong?


Solution

  • The syntax for Q objects is exactly the same as for filters: that is, you need to pass a keyword and a value, not an expression.

    self.bloglist_articles.exclude(
        Q(image_link='') | Q(image_file='')
    )