Pamk
Pamk

Reputation: 13

Django ManyToManyField reverse Relationship

I would like to do a reverse relationship on my table Tickets.

Here is my model :

class Tickets(models.Model):
    ticket_title = models.CharField(max_length=100)
    ticket_content = models.TextField()

class User_Detail(models.Model):
    user = models.OneToOneField(User)
    tickets = models.ManyToManyField(Tickets, blank=True, null=True)

I create my ticket like that :

ticket = Tickets.objects.create(ticket_title="test", ticket_content="test content")

request.user.user_detail.tickets.add(ticket)

and the thing I'm having an issue to do is to get the username of the guy who post the ticket, (without request.user)

so I tried like that :

ticket = Tickets.objects.get(pk=1)

ticket.user_detail_set.user.username

but I get

AttributeError: 'ManyRelatedManager' object has no attribute 'user'

Thanks you for watching, I hope you'll understand.

Upvotes: 1

Views: 439

Answers (1)

mipadi
mipadi

Reputation: 411340

Since you set up a many-to-many relationship, a Ticket may have many User_Detail objects. Therefore, Ticket.user_detail_set is a manager, not a single object. You could get the first user associated with a Ticket like this:

ticket.user_detail_set.first().user.username

But it sounds like you actually want a one-to-many relationship between Ticket and User_Detail, meaning you actually want Ticket to have a foreign key relationship. Your models should probably look like this:

class User_Detail(models.Model):
    user = models.OneToOneField(User)

class Ticket(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=100)
    contents = models.TextField()

Then you can do:

ticket = Ticket.objects.get(pk=1)
user = ticket.user

You might even be able to drop the User_Detail model entirely, unless you use it elsewhere in your application and/or it has more fields than what is shown here.

Upvotes: 2

Related Questions