Home > Software engineering >  Filter model assigned to user , ManyToManyField - Django
Filter model assigned to user , ManyToManyField - Django

Time:09-01

new to django and I am finding it hard to know what to search and what questions to ask sooo....here it goes...

I have a model named Obiectiv to which I have assigned users in the admin panel using manytomanyfield.

models.py:

class Obiectiv(models.Model):
    numeObiectiv = models.CharField(max_length=250)
    color = models.CharField(max_length=6, choices=COLOR_CHOICES, default='green')
    user = models.ManyToManyField(User)

I want that when the user is logged in, he is able to see only the models that have been assigned to him:

views.py

@login_required
def home(request):   
    obiective  = Obiectiv.objects.all()
    return render(request, 'home.html', context={"obiective":obiective})

With the code in the views.py it display all the Obiectiv models.

home.html

{% for obiectiv in obiective %}
        <div >
            <div >
                <div >
                    <div >
                        <div >
                            <div >Total Categories</div>
                            <div >{{ obiectiv.numeObiectiv|intcomma }}</div>
                        </div>
                        <div >
                            <div >
                                <i ></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}

thank you in advance.

CodePudding user response:

In Django, when we have a many-to-many relationship, Django maps the set of objects on both sides of the relationship: https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/

I mean, you can access the Obiectiv.users and you can also access the User.obiectiv_set (the other side of the relation).

Then, you can rewrite your view to this:

@login_required
def home(request):   
    obiective  = request.user.obiectiv_set.all()
    return render(request, 'home.html', context={"obiective":obiective})

Hope it can help you!

  • Related