Reputation: 25554
I'm with some trouble getting this code to work:
count_bicycleadcategory = 0
for item_bicycleadcategory in some_list_with_integers:
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' + str(item_bicycleadcategory) + ')' % count_bicycleadcategory
count_bicycleadcategory = count_bicycleadcategory + 1
I'm getting an error:
Type Error, not all arguments converted during string formatting
My question is: Any clue on how I pass the "item_bicycleadcategory" to the exec expression?
Best Regards,
Upvotes: 0
Views: 246
Reputation: 8548
for python 2.7 you could use format:
string = '{0} give me {1} beer'
string.format('Please', 3)
out:
Please give me 3 beer
you could do many things with format
, for example:
string = '{0} give me {1} {0} beer'
out:
Please give me 3 Please beer.
Upvotes: 1
Reputation: 7357
First, exec
is even more dangerous than eval()
, so be absolutely sure that your input is coming from a trusted source. Even then, you shouldn't do it. It looks like you're using a web framework or something of the sort, so really don't do it!
The problem is this:
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' + str(item_bicycleadcategory) + ')' % count_bicycleadcategory
Take a closer look. You're trying to put the string formatting argument to a single parentesis with no format strings with ')' % count_bicycleadcategory
.
You could do this:
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' % count_bicycleadcategory + str(item_bicycleadcategory) + ')'
But what you really should be doing is not using exec
at all!
Create a list of your model instances and use that instead.
Upvotes: 2
Reputation: 2457
try this :
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=%s)' % (count_bicycleadcategory, str(item_bicycleadcategory))
(you mustn't mix %s
and string +
concatenation at the same time)
Upvotes: -1
Reputation: 10008
Try this:
exec 'model_bicycleadcategory_%d.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=%d)' % (count_bicycleadcategory, item_bicycleadcategory)
Upvotes: -2
Reputation: 1700
You are already using python's format syntax:
"string: %s\ndecimal: %d\nfloat: %f" % ("hello", 123, 23.45)
More info here: http://docs.python.org/2/library/string.html#format-string-syntax
Upvotes: 3