本文介绍了ListField与ForeignField在django-nonrel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来很难找到一个在django-mongo-engine中使用ListField与ForeignField的完整示例。我的逻辑如下所示,

  class GameSession(models.Model):
#id =>令牌,是全局唯一的随机码
id = models.CharField(max_length = 45,primary_key = True)
def save(self,* args,** kwargs):
如果不是自己。 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))

在其他地方我这样做,

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

所以在数据库里面,self.game_session这个字段就是这样的东西,比如$ / $ $ $ $ $ $ $ $ $ $ $ u $ u u u u u u u u u u u u u u u u u u u u u u u u u 'GameSession对象']

它不能存储game_session元素的PK。如何正确使用ListField(插入,检索为外部模型,删除)?或者仍然不支持使用ForeignField的ListField?

解决方案

使用:

  self.game_session.append(game_session.id)

当将条目保存到ListField中时,使用ForeignKey不是自动,但是当您需要引用这些对象时,ForeignKey将为您提取对象。


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?

解决方案

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.

这篇关于ListField与ForeignField在django-nonrel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 09:54