1

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

1
  • 1
    Why would you use values()? Why would you call list? Why would you use range? Why are you using an index? Why not just for item in Item.objects.all(): print(item.active)? Commented Nov 20, 2019 at 15:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't use all() if you don't need, it overloads yours db.
@Unknown123: You can not iterate over .objects is a Manager, not a QuerySet. You need at least .filter(..), .all(..), etc. to construct a QuerySet. As the Zen of Python says: explicit over implicit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.