2👍
✅
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.
Source:stackexchange.com