1

It seems hard to find a complete example of using ListField with ForeignField in django-mongo-engine.. my logic looks like below,

class GameSession(models.Model):
    # id => token, is global unique random code
    id = models.CharField(max_length=45, primary_key=True)
    def save(self, *args, **kwargs):     
        if not self.pk:
            self.pk = util.get_random_string(32)  
        super(GameSession, self).save(*args, **kwargs)

class GameUser(models.Model):
    ...
    game_session = fields.ListField(models.ForeignKey(GameSession))

in somewhere else I do like this,

game_session = GameSession()
game_session.save()
self.game_session.append(game_session)
self.save()

So inside the db, the field self.game_session is something like

(Pdb) self.game_session
[u'GameSession object']

It can't store PK of the game_session elements. How to correctly use ListField (insert, retrieve as Foreign Model, remove)? or it still does not support ListField with ForeignField?

Nicolas Cortot
  • 6,591
  • 34
  • 44
Jason Xu
  • 2,903
  • 5
  • 31
  • 54

1 Answers1

1

Use:

self.game_session.append(game_session.id)

Using the ForeignKey isn't quite as "automatic" when saving entries into the ListField, but when you need to reference those objects, the ForeignKey will fetch the object for you.

dragonx
  • 14,963
  • 27
  • 44
  • Thanks. Btw, is it lazy evaluation like other django model objects that if I dont get the attribute value, db access won't be triggered? – Jason Xu Jan 02 '13 at 02:55
  • I would guess so, but I haven't actually tested to confirm it. – dragonx Jan 02 '13 at 14:41