0
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?

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
doniyor
  • 36,596
  • 57
  • 175
  • 260

2 Answers2

2

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='')
)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • And exclude instead of filter. The point is that `image_link != ""` is an expression which presupposes the existence of a variable "image_link", whereas `image_link=""` is (in this case) a keyword argument with the value "". – Daniel Roseman Oct 17 '14 at 12:12
1

@Daniel gave you the answer, but really your entire method could be simplified to:

def get_first_article_image(self):
   q = self.bloglist_articles.exclude(image_link='', image_file='')
   if q.exists():
      return q[0]
   return None

In your template:

{% if bloglist_obj.get_first_article_image %}
   <a href="{{ bloglist_obj.get_first_article_image.image_link }}">
      <img src="{{ bloglist_obj.get_first_article_image.image_file.url }}">
   </a>
{% endif %}
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284