0

I have app in Django 1.8 and I want to take last object (based on pub_date) and set for this object filed is_mainteaser on True and rest ssould be set on False.

Here is my code, but latest object hasn't field set to True.

class ArticleListView(ListView):
    model = Article
    queryset = Article.objects.order_by('-pub_date')

    def get_context_data(self, **kwargs):
        context = super(ArticleListView, self).get_context_data(**kwargs)
        lates_object = Article.objects.latest('pub_date')
        lates_object.is_mainteaser = True
        return context

Here is my model:

class Article(model.Models):
    title = models.CharField(max_length=255)
    short_text = models.TextField(max_length=10000, default='')
    image = FilerImageField(null=True)
    pub_date = models.DateTimeField('date published')
    online_from = models.DateTimeField('online from', blank=True)
    online_to = models.DateTimeField('online to', blank=True)
    position = models.PositiveIntegerField(default=0)
    is_mainteaser = models.BooleanField(default=False)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['position']
Zagorodniy Olexiy
  • 2,132
  • 3
  • 22
  • 47
git-e
  • 269
  • 1
  • 4
  • 15
  • You never save it... but then why are you doing this in the `get_context_data`? – Sayse Dec 19 '16 at 13:13
  • @Sayse it should be in another method? – git-e Dec 19 '16 at 13:20
  • Well I don't understand what you're setting it for so I can't tell you, it looks like it would be wasteful though as this would get saved every time someone visits the list view – Sayse Dec 19 '16 at 13:26
  • @Sayse I want to set always `is_mainteaser` on `True` for the latest object and rest object should be set on `False`. – git-e Dec 19 '16 at 13:29

1 Answers1

0

When you have object instance and change model attribute you must save instance. Example:

lates_object = Article.objects.latest('pub_date')
lates_object.is_mainteaser = True
lates_object.save()

I think better for this solution is use django signals or action when you add new article. In ListView is't good solution to do it that.

SmoQ
  • 293
  • 2
  • 10