user2869934
user2869934

Reputation: 1599

Django query many-to-many field

I have these two models.

class Tickets(models.Model):
    id = models.CharField(primary_key=True, max_length=12)
    recipients = models.ManyToManyField(CustomUser)
    title = models.CharField(blank=True, max_length=100)

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(primary_key=True,)
    user_name = models.CharField(blank=False, max_length=20)

In Tickets model, recipients may include multiple users.
I'm trying to
1. Read how many tickets does specific user has.
2. Regroup Tickets by recipients to get this kind of output in template.

user_name1
   Ticket.id
   Ticket.title
user_name2
   Ticket.id
   Ticket.title
user_name3
   Ticket.id
   Ticket.title

I was trying really hard on "regroup", but not much result...
Could someone give me some guidance?

Upvotes: 0

Views: 1025

Answers (1)

zaidfazil
zaidfazil

Reputation: 9235

If you just want to get tickets of each user you could just use the reverse relation,

users = CustomUser.objects.all()

and in template,

{% for user in users %}
    {{ user.username }}
    {% for ticket in user.ticket_set.all %}
        {{ ticket.id }}
        {{ ticket.title }}
    {% endfor %}
{% endfor %}

Upvotes: 1

Related Questions