ListField with ForeignField in django-nonrel

我的梦境 提交于 2019-12-13 02:18:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!