0

Is there a better way to do the following in a django Model method? The following looks quite verbose, as I could do the same in the SQL shell with one line:

class ItemMaster(models.Model):
    ...

    @classmethod
    @transaction.commit_manually
    def update_imdb_rank(self):
        '''
        Update all ranks from the IMDbEntry table
        '''
        cursor = connection.cursor()
        cursor.execute("UPDATE main_itemmaster i JOIN mturk_imdbentry m USING (imdb_url) SET i.imdb_rank=m.imdb_rank")
        transaction.commit()
4
  • Do you have a foreign key from main.ItemMaster to mturk.IMDBEntry or vice versa? And is it based on imdb_url? Commented Jul 8, 2015 at 1:30
  • There's not a foreign key on either, they'll just be the same. Commented Jul 8, 2015 at 1:38
  • 1
    Is there a reason not to use the ORM to do the update? Commented Jul 8, 2015 at 1:41
  • If you were hoping to use the ORM, then you won't be able to unless you add a FK or a generic foreign key relationship between the two. Commented Jul 8, 2015 at 1:41

1 Answer 1

2

You can use the with statement to reduce verbosity if you wish:

class ItemMaster(models.Model):
    ...

    @classmethod
    def update_imdb_rank(self):
        with transaction.atomic():
            cursor = connection.cursor()
            cursor.execute("UPDATE main_itemmaster i JOIN mturk_imdbentry m USING (imdb_url) SET i.imdb_rank=m.imdb_rank")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.