I am trying to filter all reviews that correspond to listings created by a certain viewer. The purpose is to put all the reviews someone has received on their listings on a profile page. I am able to use get_context_data to pull in the listing reviews, but I want to filter on a relationship within the listing itself.
Views.py:
class ProfileDetailView(DetailView):
model = Profile
template_name = 'account/profile_detail.html'
context_object_name = 'profile_detail'
def get_object(self):
return self.request.user.profile
def get_context_data(self, **kwargs):
context = super(ProfileDetailView, self).get_context_data(**kwargs)
context['reviews'] = RentalListingReviews.objects.filter(RentalListing.lender = self.request.user)
return context
Models.py:
class RentalListing(models.Model):
item_id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
lender = models.ForeignKey(
get_user_model(),
on_delete = models.CASCADE,
)
item_name = models.CharField(max_length=200)
def __str__(self):
return self.item_name
def get_absolute_url(self):
return reverse('rental_listing_detail', args=[str(self.item_id)])
class RentalListingReviews(models.Model):
listing = models.ForeignKey(
RentalListing,
on_delete = models.PROTECT,
related_name = 'listing_reviews',
)
review = models.TextField(max_length = 1000)
author = models.ForeignKey(
get_user_model(),
on_delete = models.PROTECT,
)
def __str__(self):
return self.review
def get_absolute_url(self):
return reverse('rental_listing_detail', args=[str(self.listing.item_id)])
CodePudding user response:
You are trying to assign a RentalListing field in a function call.
context['reviews'] = RentalListingReviews.objects.filter(RentalListing.lender = self.request.user)
Should be ->
context['reviews'] = RentalListingReviews.objects.filter(lender = self.request.user)
CodePudding user response:
It should be:
RentalListingReviews.objects.filter(listing__lender = self.request.user)