Matt Schucker
Matt Schucker

Reputation: 67

Django: Accessing full User information via ManyToMany field

everyone- I'm new to Django and working on my first big project and I'm having trouble with accessing default Django User model information via a ManyToMany relationship. I've spent a great deal of time searching and can't crack it.

models.py

class Event(models.Model):
  event_name = models.CharField(max_length=200, null=True, unique=True)
  #etc...

class School(models.Model):
  user = models.ManyToManyField(User)
  event = models.ForeignKey(Event, null=True, on_delete=models.PROTECT)
  #etc...

My url contains the id of the Event, so...

views.py

def schools(request, pk):
   event = Event.objects.get(id=pk)
   school = School.objects.filter(event=event)
   return render(request, 'accounts/schools.html', {'event':event, 'school':school})

template

{% for school in school %}
   <tr>
      <td>{{school.name}}</td>
      <td>{{school.user.all}}</td>
{% endfor %}

On my template, I'm able to use {{school.user.all}} to get me a Queryset displayed with the username of each User, but I want the first_name and last_name and can't see to figure out how to get that..

Thank you for any suggestions. I greatly appreciate your time!

Upvotes: 0

Views: 770

Answers (2)

hrmncd
hrmncd

Reputation: 1045

You should include both schools and users to your context.

You can do this with a dictionary. Add each school as a key, and users of each school as its values. Then you can pass this dictionary to your template.

View function:

def schools(request):
    school_dict = dict()
    schools = School.objects.all()
    for school in schools:
        school_dict[school] = school.user.all()
    return render(request, 'accounts/schools.html', {'schools': school_dict})

And in your template:

{% for school, users in schools.items %}
    <h3>{{ school.title }}</h3>
    <table>
    {% for user in users %}
        <tr>
        <td>{{ user.first_name }}</td>
        <td>{{ user.last_name }}</td>
        </tr>
    {% endfor %}
    </table>
{% endfor %}

Upvotes: 1

Matt Schucker
Matt Schucker

Reputation: 67

I was able to add this to my school model to get what I wanted:

    def director(self):
        test = ",".join([str(p) for p in self.user.all()])
        user = User.objects.get(username=test)
        return user.first_name + " " + user.last_name

HOWEVER: if there is more than one user associated with "School" it displays blank

Upvotes: 0

Related Questions