0

I'm creating a dictionary for my model and use the dictionary to make json data.

class MyImage(models.Model):
  ...
  album = models.ForeignKey(Album)
  def to_dict(self):
     result = {}
     result['id'] = self.id
     .. additional data...
     result['album_id'] = self.album.id  // database hit
     result['album_title'] = self.album.title  // another database hit
     result['album_something'] = self.album.something // another hit

I just found out that to create a dictionary of MyImage I need 1+3 as noted in the comment above.

Can I cut down the DB hit to 1+1 instead of 1+3 somehow?

eugene
  • 39,839
  • 68
  • 255
  • 489

2 Answers2

0

you can manage with 1 hit capture the data to a Value Object (simple class wich has all the database entity attributes) - 1 hit

and serve/construct your json data from the Value Object.

TheWhiteRabbit
  • 15,480
  • 4
  • 33
  • 57
  • I don't fully understand. Can you elaborate? – eugene Jan 08 '13 at 03:49
  • have one query / db method to extract all the values from db. and cache / store them to a Class. – TheWhiteRabbit Jan 08 '13 at 03:53
  • have one query / db method to extract all the values from db. and cache / store them to a Class. and then use the fields as an when requiered instead of going to the db for every field. makes sense ? – TheWhiteRabbit Jan 08 '13 at 03:57
  • Yes I understand the concept, but how? use raw sql? – eugene Jan 08 '13 at 05:00
  • use [link](http://stackoverflow.com/questions/7615357/django-querysets-memcached-best-practices) and [link](http://stackoverflow.com/questions/4631865/caching-query-results-in-django) – TheWhiteRabbit Jan 08 '13 at 08:50
0

Use select_related.

From the Docs

Returns a QuerySet that will automatically "follow" foreign-key relationships, selecting that additional related-object data when it executes its query. This is a performance booster which results in (sometimes much) larger queries but means later use of foreign-key relationships won't require database queries.

# Hits the database.
e = Entry.objects.get(id=5)

# Hits the database again to get the related Blog object.
b = e.blog

# Hits the database.
e = Entry.objects.select_related().get(id=5)

# Doesn't hit the database, because e.blog has been prepopulated
# in the previous query.
b = e.blog
user710907
  • 762
  • 5
  • 12
  • Yes this works. I would have to add select_related() to most of my query. Still curious though `can you not do album=self.album and album.id, album.title would serve the results from the cache. – karthikr`. Isn't there a way to do this? – eugene Jan 08 '13 at 06:56
  • looks like django 1.5 will support the preloading. – eugene Jan 22 '13 at 12:08