Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
How to reference self.something in Django models.py?

I'm working on a Django project that uses models. I want to somehow access the highest bid on that listing at all times (as listing.highest_bid) or some other way if there's a better solution. What I tried in the code snippet below for the highest_bid doesn't seem to work, it gives me an AttributeError (AttributeError: 'str' object has no attribute 'bids'). How can I access a model's own parameter's values and filter them to my liking?

class Listing(models.Model):
        user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listings")
        title = models.CharField(max_length=100)
        description = models.CharField(max_length=1000)
        starting_bid = models.PositiveIntegerField()
        picture = models.TextField(max_length=200, default='static/auctions/notfound.png')
        category = models.ForeignKey(Category, on_delete=models.CASCADE,related_name="listings") 
        is_active = models.BooleanField()
        highest_bid = self.bids.aggregate(Max('price'))

        def __str__(self):
            return f"{self.title}"
    
    
    class Bid(models.Model):
        listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids")
        user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bids")
        price = models.PositiveIntegerField()
        # time TODO
        def __str__(self) -> str:
            return f"Bid #{self.id}"
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can simply use @property to return a such as computed field

class Listing(models.Model):
   # Some fields
   
   @property
   def highest_bid(self):
       # Access the Listing bids by reverse foreign key and retrieve the first with highest price
       return self.bids.order_by('-price').first()

Note : Each time you do listing.highest_bid the function will be executed to return the result (Dynamic)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!