I have this code for table populating.
def add_tags(count):
print "Add tags"
insert_list = []
photo_pk_lower_bound = Photo.objects.all().order_by("id")[0].pk
photo_pk_upper_bound = Photo.objects.all().order_by("-id")[0].pk
for i in range(count):
t = Tag( tag = 'tag' + str(i) )
insert_list.append(t)
Tag.objects.bulk_create(insert_list)
for i in range(count):
random_photo_pk = randint(photo_pk_lower_bound, photo_pk_upper_bound)
p = Photo.objects.get( pk = random_photo_pk )
t = Tag.objects.get( tag = 'tag' + str(i) )
t.photos.add(p)
And this is the model:
class Tag(models.Model):
tag = models.CharField(max_length=20,unique=True)
photos = models.ManyToManyField(Photo)
As I understand this answer : Django: invalid keyword argument for this function I have to save tag objects first (due to ManyToMany field) and then attach photos to them through add()
. But for large count
this process takes too long. Are there any ways to refactor this code to make it faster?
In general I want to populate Tag model with random dummy data.
EDIT 1 (model for photo)
class Photo(models.Model):
photo = models.ImageField(upload_to="images")
created_date = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User)
def __unicode__(self):
return self.photo.name