Home > Mobile >  Query database only on a particular column django ORM
Query database only on a particular column django ORM

Time:11-09

I am new to Django and couldnt find the answer i was looking for so bear with me

I have a model class called bid on an auction app that stores all bids that were placed on all items:

class Bid(models.Model):
    title = models.CharField(max_length=64, blank=True)
    date_time = models.DateTimeField(default=timezone.now, blank=True)
    price = models.DecimalField(max_digits=4, decimal_places=2)
    user = models.CharField(max_length=64)

now i want to query this table and have it return to me ALL the bid prices that were placed on a particular item, i have this line:

bids = Bid.objects.all().filter(title=title)

that returns all objects with that title, but i dont care for the other columns of this object, i just want the prices

this is kinda stupid but i did try it:

bids = bids.price

ofcourse it didnt work

CodePudding user response:

I have gone through your question and as per my understanding you need to fetch only the prices based on the title of bid. If this is the scenario then you can fetch it in this way:

bids = Bid.objects.all().filter(title=title).values_list("price", flat = True)

I hope this helps you. Please respond to this message if your having any difficulty fetching.

Thanks, Regards.

CodePudding user response:

You need to use a loop to get all the prices. Like this:

bids = Bid.objects.filter(title=title)
for bid in bids:
    print(bid.price)

This is because the filter query returns a list and if you want the price of every bid you need to loop in every object coming in the filter query.

You can go through the documentation here: https://docs.djangoproject.com/en/4.1/topics/db/queries/#retrieving-specific-objects-with-filters

  • Related