cristian9804
cristian9804

Reputation: 93

Iterating Through a Database Django

I have a model in my database called Item. This is the model

class Item(models.Model):
    item_title = models.CharField("Item title: ", max_length=50)
    item_description = models.CharField("Item description: ", max_length=200)
    starting_price = models.FloatField( default = 0)
    picture = models.ImageField(upload_to = 'gallery')
    finishTime = models.DateTimeField("Finish time: ")
    ownerID = models.ForeignKey(User, on_delete = models.CASCADE)
    higestBid = models.FloatField()
    highestBidderID = models.IntegerField(blank=True, default=-1)
    active = models.BooleanField(default = True)

I want to create a function in views.py , which will check the 'active' field of each item in the database. How can I do that? I have tried to do this:

items = list(Item.object.values())
for i in range(items):
  print(item[i].active)

However it does not work. Any help is appreciated

Upvotes: 1

Views: 2311

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You should iterate over the queryset itself:

for item in Item.objects.all():
  print(item.active)

Please do not use .values() [Django-doc]. You should only use that for some specific cases, like grouping on a certain value. By working with objects, you will still use model objects, and thus certain logic you added on that object, is still accessible.

Furthermore it is often better not to use list(..). A QuerySet is lazy, and thus if you somehow never iterate over it, then it will not make the query. Furthermore you can then do extra filtering on an existing QuerySet.

Upvotes: 1

Related Questions