Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda