tags:

views:

39

answers:

2

Hi,

I wonder if there is a way to make a copy of one db item?

e.g. I have a model

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

So if I added one item, how can i clone it 100 times for testing?

+1  A: 
# Create a bunch of new objects
for i in xrange(0,100):
    new_cat = Category(slug='a-slug', name="My Name")
    new_cat.save()

If you're just looking to populate your database for testing purposes, you may want to look at using fixtures instead.

Josh Wright
But to create fixture you need objects in db (to dump)....Correct? What if my category model has 10 fields?
Oleg Tarasenko
Why does the number of fields matter?
Josh Wright
So I do add them to the constructor?
Oleg Tarasenko
+1  A: 

If the model has an autoincrement PK (the default) then you can create or retrieve the object once, then wipe the PK before saving it:

row = SomeModel(...)
for i in xrange(100:
  row.pk = None
  row.save()
Ignacio Vazquez-Abrams