First, here is my Location model. It has one ManyToManyField called members.
Model:
class Location(models.Model):
name = models.CharField(max_length=200)
# ...
members = models.ManyToManyField(User, related_name="members")
# ...
(Note, "# ..." replaces more fields)
And then in a view I did this.
DetailView
class LocationDetailView(DetailView):
model = Location
context_object_name = "location"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
location = Location.objects.filter(pk=self.get_object().pk)
context["members"] = location.members.all()
return context
Error
'QuerySet' object has no attribute 'members'
CodePudding user response:
Your location
is not a Location
object, but a QuerySet
that contains one Location
object. Fetching this however is not necessary, you can work with:
class LocationDetailView(DetailView):
model = Location
context_object_name = 'location'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['members'] = self.object.members.all()
return context
But in fact you do not need to pass the members
to the context: in the template you can work with:
{% for member in location.members.all %} … {% endfor %}
CodePudding user response:
I found the misake, it's
location = Location.objects.get(pk=self.get_object().pk)
and not
location = Location.objects.filter(pk=self.get_object().pk)