Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda