Take last object in queryset and set value in field

243 views Asked by At

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']
1

There are 1 answers

0
SmoQ On

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.