问题
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?
回答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.
来源:https://stackoverflow.com/questions/14101834/listfield-with-foreignfield-in-django-nonrel