[Answered ]-Avoid duplication in Django for loop with a many to many relationship

1đź‘Ť

âś…

You can simplify your models a lot in my opinion. You point from tag in NoteModel to NoteTagModel and vice versa & I don’t think it is needed.
Also TaggedModel seems superfluous. At least if there isn’t a specific reason to link it like you did.

class NoteModel(models.Model):
    note = models.CharField(max_length = 5000)
    note_title = models.CharField(max_length=500, blank=False, null=True)
    project = models.ForeignKey(IndividualProject, on_delete=models.CASCADE, related_name="note_projects", blank=False, null=True)
    # plural
    tags = models.ManyToManyField(NoteTagModel, related_name="tags", blank=False)
    
    def __str__(self):
        return self.note_title
    
class NoteTagModel(models.Model):
    # usually there is no need to point here again to the same model thats already pointing to this one
    tag_title = models.CharField(max_length=200, default="General")
    
    def __str__(self):
        return self.tag_title

If you want to access reverse from NoteTagModel to NoteModel, you can do the following eg:

for tag in NoteTagModel.objects.all():
    for note in tag.nodemodel_set.all():
        print(note.note_title)
        …

(I put the html classes in double quotes)

<div class="note_overview_container">
    {% for note in notes %}
        <div class="individual_note_container"> 
            <div class="note_title">
                {{ note.note_title }}
            </div>

            <!-- loop over all the tags related to the note -->
            {% for tag in note.tags.all %}
                <div class=”tag_title”>
                    {{ tag.tag_title }}
                </div>

                <ul class="tag_commentary">
                    <!-- commentary in commentary shouldnt be named the same -->
                    {% for comment in commentary %}
                        {% if note_tag == comment.tag_title %}
                            {% if note == comment.note %}
                                <li>{{ comment.tag_commentary }}</li>
                            {% endif %}
                        {% endif %}
                    {% endfor %}
                </ul>
            {% endfor %}
        </div>
    {% endfor %}    
</div>
👤Alicia Sch.

Leave a comment