I have two models with One-to-Many relationship; Listing, and Bids. Is it possible to retrieve and display a list of Bid objects' bid_price in Listing's str method?
The code provided below crashes the server and I am not sure of the correct keywords to search for.
I understand how listing.bid_set works in the Shell or view, but I am not sure how to make it work here.
class Listing(models.Model):
title = models.CharField(max_length=64)
def __str__(self):
bid_objects = Bid.objects.all().filter(listing__id=self.id)
price_list = []
for bid_object in bid_objects:
price_list.append(bid_object.bid_price)
return f"{self.title}, {price_list}"
class Bid(models.Model):
listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing_bids")
bid_price = models.DecimalField(max_digits=6, decimal_places=2)
Thanks for your help.
Since you specified related_name='listing_bids'
, it means you access the related Bid
s with self.listing_bids
:
class Listing(models.Model):
title = models.CharField(max_length=64)
def __str__(self):
bid_objects = self
return f'{self.title}, {bid_objects}'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.