Why isn't this view returning data?

single_joke works. joke_id in joketag is an fk back to joke. single_tag isn’t returning results. There are multiple records per id in joketag. What am i doing wrong?

def detail(request, id):

    single_joke = Joke.objects.get(joke_id=id)

    single_tag = JokeTag.objects.filter(joke_id=id)

    context = {

        'single_joke': single_joke,

        'single_tag': single_tag


    return render(request, 'blue.html', context)

single_tag worksif I use.get and joke_tag_id, but I don’t want that


What do you mean “I don’t want that”? What do you want?

Part of the post got cut out. See original post.

You still haven’t defined what it is that you want to see happen here. You haven’t shown the models involved, nor have you provided the template that you are attempting to render.

We need to see a lot more detail before this can be diagnosed.

I am trying to get this to show me the data from the tag column in the table.

single_tag = JokeTag.objects.filter(joke_id=id)


{{ single_tag.tag }}


class JokeTag(models.Model):
    joke_tags_id = models.AutoField(primary_key=True)
    joke_id = models.ForeignKey('Joke', models.CASCADE)
    tag = models.ForeignKey('Tag', models.CASCADE)

    class Meta:
        managed = True

To clarify:

  • Your request is being supplied the pk of Joke.

  • There are 0 or more instances of JokeTag related to Joke.

  • You can easily retrieve the entire set of JokeTag using the related manager (e.g. some_joke.joketag_set.all())

But you say you’re looking for one JokeTag.
Which JokeTag do you want?

I’m trying to get all records from JokeTag that have the specified joke_id. I tried .all originally, but it doesn’t work.

What did you try?

More specifically, did you try using the related manager as shown in my previous reply?

Also, given that you are going to retrieve a query set, how are you rendering the multiple results you may get from such a query?

I tried

single_tag = JokeTag.joketag_set.all()

Ok, so that returns a queryset.

What did you do with it from there?

Paste error…

I tried

single_tag = JokeTag.joketag_set.all()

Because Joke itself doesn’t reference JokeTag.

You were closer to being right the first time - this last posting makes no sense.

I think you may need to review the docs on foreign keys and reverse foreign key access - see Related objects reference | Django documentation | Django

The first way will never work. let me test something

If you have:

joke_tags = single_joke.joketag_set.all()
is a queryset containing all JokeTag related to single_joke.

Thanks. apparently I had it right at the very beginning but something was off with my loop… It works. Thanks for talking me through it.

{% for tag in single_tag %}
{{ tag.tag }}
{% endfor %}