[Answer]-Django reverse lookup of a OneToOneField from a ManyToManyField

1πŸ‘

βœ…

In your place I would do :

class Tag(models.Model):
    name = models.CharField(max_length=64, unique=True)

class Poem(models.Model):
    title = models.CharField(max_length=256)
    thetext = models.TextField()
    tags   = models.ManyToManyField(Poem)

so :

def tag_page(request, tag_name):
    poems_sets = []
    tag = get_object_or_404(Tag, name=tag_name)
    poems = Poem.objects.filter(tags__name=tag).order_by('-id')             
    for p in poems:                
        usersp = UserPoem.objects.filter(poem=p)
        for u in usersp:
            poems_sets.append((p, u))
    return locals() 

template :

{% for poem,usersp in poems_sets %}
    {{poem.title}}
    {{poem.thetext}}
    {% for u in usersp %}
        {{u.date}}
        {{u.user}}
    {% endfor %}
{% endfor %}               
πŸ‘€Armance

Leave a comment