1

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.

1 Answer 1

3

Since you specified related_name='listing_bids', it means you access the related Bids with self.listing_bids:

class Listing(models.Model):
    title = models.CharField(max_length=64)

    def __str__(self):
        bid_objects = self.listing_bids.values_list('bid_price', flat=True)
        return f'{self.title}, {bid_objects}'
Sign up to request clarification or add additional context in comments.

2 Comments

If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set
I get it now, in my case, bid_set will work if I don't specify related_name. Thanks for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.