itssubas
itssubas

Reputation: 163

How to get data connected by ForeignKey?

I'm new in Django. I'm trying to retrieve all the Tags associated with a Question.

I have two classes on models.py.

class Questions(models.Model):
    title = models.CharField(max_length=500)
    description = models.TextField(blank=True)

class Tag(models.Model):
    name = models.CharField(max_length=50)
    tag_on = models.ForeignKey(Questions, on_delete=models.CASCADE)

My views.py.

class QuestionListView(ListView):
    model = Questions #assign model to display
    template_name = 'index.html'

class TagListView(ListView):
    model = Tag
    template_name = 'index.html'
    context_object_name = 'tag_list'
    queryset = ?

I have added this to my index.html.

{% for val in object_list %}
  {{ val.id }} <br>
  {{ val.title }} <br>
{% endfor %}

{% for tag in tag_list %}
  {{ tag }}
{% endfor %}

I have tried few queryset like this but none of them worked.

queryset = Tag.objects.all().get(Tag.id=Questions.id)
queryset = Tag.objects.select_related('tag_on__id').get()

How do I define queryset properly to address this problem?

Upvotes: 0

Views: 75

Answers (2)

Vishal Raghavan
Vishal Raghavan

Reputation: 483

You can just try doing this.

queryset=Tag.objects.filter(tag_on__id=<your_id>)

As far as how to render it in the template.

You can do something like this.

def view(request):
  return render(request,'index.html',context={queryset:Tag.objects.filter(tag_on__id=<your_id>)})

and in your index.html

{% for i in queryset %}
  {{i.name}} // or any fields that you want
{% endfor %}

For class based approach:

from django.views.generic import TemplateView
class yourview(TemplateView):
    template_name = "index.html"

    def get_context_data(self, kwargs):
      context = super(yourview, self).get_context_data(**kwargs)
      context['queryset'] = Tag.objects.filter(tag_on__id=<your_id>)
      return context

Upvotes: 1

Dawn T Cherian
Dawn T Cherian

Reputation: 5416

If you want to retrieve all the Tags associated with a particular Question:

question = Questions.objects.get(<some_condition>)
queryset = Tag.objects.filter(tag_on=question)

Upvotes: 1

Related Questions