如何让两个模型引用对方Django [英] How to have two models reference each other Django

查看:106
本文介绍了如何让两个模型引用对方Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

class Game(models.Model):
    title = models.CharField(max_length=50)
    summery = models.CharField(max_length=500)
    key = models.IntegerField()
    pin = models.CharField(max_length=12)
    complete = models.BooleanField()
    invite_sent = models.DateTimeField()
    on = models.ForeignKey(Member, blank = True) #<----


class Member(models.Model):
    email = models.CharField(max_length=100)
    color = models.CharField(max_length=11)
    game = models.ForeignKey(Game) #<----

on外键链接到其中一个成员(谁转过来它是)。游戏的所有成员都将他们的游戏外键设置为他们所在的游戏。问题是Django在它被声明之前不会让我引用一个类,因为我不能同时声明它们。

The "on" foreign key links to one of the members (who's turn it is). All members of a game have their "game" foreign key set to the game they are on. The problem is that Django won't let me reference a class before it has been declared, and since I can't declare them simultaneously...

编辑:要清除这就是一个例子。如果有五个成员玩一个游戏,那么五个人都会有外键游戏。另一方面,这个游戏对于特定成员来说会有一个外键。

To clear things up, here's an example. If there were five members playing one game, all five would have foreign keys to the game. The game on the other hand would have one foreign key to the particular member who's turn it was.

推荐答案

ForeignKey字段的Django文档指出:


如果您需要在尚未定义的模型上创建关系,则可以使用模型的名称,而不是模型对象本身。

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself.

所以在你的情况下,这将是:

So in your case, that would be:

class Game(models.Model):
    # Other fields...
    on = models.ForeignKey('Member', blank = True)

class Member(models.Model):
    # Other fields...
    game = models.ForeignKey(Game)

这篇关于如何让两个模型引用对方Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆