Django Models. Undefined variable

Viewed 387

Does anyone know why the itembided__currentbid is identify as an undefined variable? My models are:

class AuctionListing(models.Model):
    username = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user")
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=1000)
    startingbid = models.DecimalField(max_digits=6, decimal_places=2)
    category = models.CharField(max_length=64, blank=True)
    imgurl = models.URLField(max_length=300, blank=True)
    status = models.BooleanField(default=True)

class Bid(models.Model):
    usernameb = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userb")
    auctionitem = models.ForeignKey("AuctionListing", on_delete=models.CASCADE, related_name="itembided")
    currentbid = models.DecimalField(max_digits=6, decimal_places=2, default=0)

And the code from views.py where the issue is:

...    
from .models import User, AuctionListing, Bid

def index(request):
    q = AuctionListing.objects.filter(status=True).annotate(max_bid=Coalesce(V(0),Max(itembided__currentbid)))
    return render(request, "auctions/index.html", {
        "q":q,
    })

Any suggestions? My original Bid model had no quotes for the AuctionListing parameter, It looked like this:

auctionitem = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name="itembided")

However, after reading a disscution from StackOverflow Undefined variable in django I tried adding the quotes to the AuctionListing parameter... sadly, it didn't work.

2 Answers

You pass the name of a field as a string, right now you use an identifier, but there is no identifier with that name. Furthermore you probably want to Coalesce [Django-doc] in the opposite way, and use 0 in case that there is related Bid object. You thus can rewrite this to:

from django.db.models import Max, Value as V
from django.db.models.functions import Coalesce
from .models import User, AuctionListing, Bid

def index(request):
    q = AuctionListing.objects.filter(status=True).annotate(
        max_bid=Coalesce(
            Max('itembided__currentbid'),  # ← use a string
            V(0)  # ← use V(0) as second element
        )
    )
    return render(request, "auctions/index.html", {
        "q":q,
    })

Max(itembided__currentbid) is missing the quotes. It should be Max("itembided__currentbid")

Related