简体   繁体   中英

Looping over a specific field in a django form

Learning Django by creating an eBay like bidding application.

One of my models is a simple bid class that will record every user's bid for a particular listing.

models.py

class Bid(models.Model):
    bid = models.DecimalField(max_digits=10, decimal_places=2)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE)

forms.py

def listing_view(request, id):

    form = BidForm(request.POST or None)

    if form.is_valid():

        instance = form.save(commit=False)
        instance.user = request.user
        instance.listing_id = id

        # check bid is higher than starting bid or other bids or flash error message
        current_bid = instance.bid
        starting_bid = instance.listing.starting_bid
        query = Bid.objects.all().filter(listing=id)

In forms.py, I am writing a view to validate that the bid the user entered is larger than existing bids. It's incomplete because I am stuck on creating this comparison.

The easy way is to loop over the 'query' variable and do the comparison, but is there a more elegant solution?

I found a solution using the all() function, something like:

all(current_bid > i in my_list)

But this only works for comparing against a list, not form objects

Is there a way to loop over query (ie for each in query) and get check whether current_bid is greater than all of the 'each.bid' in 1 line?

Something like this:

all(current_bid > i for i.bid in query)

Sadly, this doesn't work. I get a NameError - name 'i' is not defined.

Thanks!

This line here:

all(current_bid > i for i.bid in query)

needs to be changed to something like this:

all(current_bid > i.bid for i in query)

Sometimes list comprehensions are confusing so I like to imagine them as normal for loops. Here's my interpretation of what you're trying to do (no guarantees of correctness):

is_biggest_bid = True
for i in query:. # writing i.bid wouldn't make sense here
    if i.bid > current_bid:
        is_biggest_bid = False
        break

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM