Home > Enterprise >  How to reference self.something in Django models.py?
How to reference self.something in Django models.py?

Time:11-20

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}"

CodePudding user response:

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)

  • Related