Frage

So I'm not sure whether to pose this as a Django or SQL question however I have the following model:

class Picture(models.Model):
    weight = models.IntegerField(default=0)
    taken_date = models.DateTimeField(blank=True, null=True)
    album = models.ForeignKey(Album, db_column="album_id", related_name='pictures')

I may have a subset of Picture records numbering in the thousands, and I'll need to sort them by taken_date and persist the order by setting the weight value.

For instance in Django:

pictures = Picture.objects.filter(album_id=5).order_by('taken_date')
for weight, picture in enumerate(list(pictures)):
    picture.weight = weight
    picture.save()

Now for 1000s of records as I'm expecting to have, this could take way too long. Is there a more efficient way of performing this task? I'm assuming I might need to resort to SQL as I've recently come to learn Django's not necessarily "there yet" in terms of database bulk operations.

War es hilfreich?

Lösung

Ok I put together the following in MySQL which works fine, however I'm gonna guess there's no way to simulate this using Django ORM?

UPDATE picture p
JOIN (SELECT @inc := @inc + 1 AS new_weight, id 
FROM (SELECT @inc := 0) temp, picture 
WHERE album_id = 5 
ORDER BY taken_date) pw
ON p.id = pw.id
SET p.weight = pw.new_weight;

I'll leave the question open for a while just in case there's some awesome solution or app that solves this, however the above query for ~6000 records takes 0.11s.

NOTE that the above query will generate warnings in MySQL if you have the following setting in MySQL:

binlog_format=statement

In order to fix this, you must change the binlog_format setting to either mixed or row. mixed is probably better as it means you'll still use statement for everything except in cases where row is required to avoid a warning like the above.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top