Saturday, June 10, 2017

Re: Filter queryset based on another model's foreign key in a class based view.

On Saturday 10 June 2017 08:22:20 Ajat Prabha wrote:

 

 

> class TopicDetailView(generic.DetailView):

> > model = Topic

> > context_object_name = 'topic'

> > template_name = 'topicdetail.html'

>

> def get_context_data(self, **kwargs):

> > context = super(TopicDetailView,

> > self).get_context_data(**kwargs)

> > context["answer"] = Answer.objects.filter(<can't figure out

> > this>)

 

Use clear and consistent names. Since this can return multiple answers, use answer_list, as in line with topic_list in your index view.

this becomes:

context['answer_list'] = self.object.answer_set.all()

 

 

 

> models.py

 

> class Topic(models.Model):

> > # Choices

> > CAT_CHOICES = (

> >

> > ('Q', 'Question'),

> > ('F', 'Feedback'),

> >

> > )

> > # Topic Database Model

> > owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)

> > category = models.CharField(max_length=3, choices=CAT_CHOICES,

> >

> > default='Q')

> >

> > title = models.CharField(max_length=256)

> > content = RichTextUploadingField(blank=True)

> > slug = models.SlugField(unique=True)

> > views = models.PositiveIntegerField(default=0)

> > answers = models.PositiveIntegerField(default=0)

 

Why is this here?

 

Is this what you want?

 

@property

def number_of_answers(self):

return self.answer_set.count()

 

 

> > tags = models.CharField(max_length=50)

> > created_at = models.DateTimeField(auto_now_add=True)

>

> def get_absolute_url(self):

> > return reverse('forum:detail', kwargs={'pk': self.pk})

>

> def __str__(self):

> > return self.title

> >

> > class Answer(models.Model):

> > topic = models.ForeignKey(Topic, on_delete=models.CASCADE)

 

This creates a property 'answer_set' on the Topic model, which is a model manager (to be precise, a RelatedManager). So you can do queryset methods on it.

 

 

> urls.py

 

> > url(r'^$', login_required(views.IndexView.as_view()),

 

Consider moving this to the view definitions:

 

class IndexView(LoginRequiredMixin, ListView):

 

(LoginRequiredMixin *must* be first).

 

 

--

Melvyn Sopacua

No comments:

Post a Comment