Eyad Sibai
Eyad Sibai

Reputation: 893

iteritems does not return all dictionary items

I'm iterating over a dictionary using iteritems() to create objects in Django. However, I found that the number of created objects is not the same of number of the dictionary objects.

On exploring this further, I discovered that the dictionary's iteritems() method is only returning 197 tuples, while the dictionary itself contains 269 items.

data = {...}
print len(data) #output: 269
for k, v in data.iteritems():
    Category.objects.create(name=k).save()
len(Category.objects.all()) #output: 197

Model definition:

class Category(models.Model):
    name = models.CharField(max_length=100)

Upvotes: 0

Views: 243

Answers (1)

Павел Тявин
Павел Тявин

Reputation: 2659

First of all, I don't recommend you use len(Category.objects.all()) to count objects. Instead, you should use

Category.objects.count()

It's not a matter of style, but efficiency. The latter uses SQL COUNT, so the number of objects is calculated not by python but by your database (mysql, sqlite, etc.)

I cannot comment on why you're getting 192 objects, not 267. My guess is it's because your create function is getting some unusable parameters - maybe k is not a string, or maybe its length exceeds 100 characters.

Can you investigate which elements didn't save and provide this information?

Upvotes: 2

Related Questions