变化与一对一不节能
关系我有两个,我使用Django的OneToOneField与模型建模,本文档以下内容:https://docs.djangoproject.com/en/2.0/topics/db/examples/one_to_one/变化与一对一不节能
class Seats(models.Model): north = models.OneToOneField('User',on_delete=models.CASCADE,related_name='north', default=None, null=True)
bridgetable = models.OneToOneField('BridgeTable',on_delete=models.CASCADE, default=None, null=True)
class BridgeTableManager(models.Manager):
def create_deal(self):
deal = construct_deal()
table = self.create(deal=deal)
s = Seats(bridgetable=table)
s.save()
return table
class BridgeTable(models.Model):
deal = DealField(default=None,null=True)
当我运行这段代码我能顺利拿到关系工作
table = BridgeTable.objects.get(pk='1') user = User.objects.get(username=username)
table.seats.north = user
table.seats.north.save()
print(table.seats.north)
打印语句打印出坐在北方的玩家的名字。但是,如果我尝试像这样再次访问表格:
table = BridgeTable.objects.get(pk='1') print(table.seats.north)
我得到“无”而不是用户名。有什么我错过了,就像我错过的保存或一些我不理解的概念?谢谢。
回答:
您应该保存座椅模型对象,它是table.seats.save()
尝试print table.seats.north
虽然table.seats.north.save()
运行节省User
对象
这里是正确的步骤:
table = BridgeTable.objects.get(pk='1') user = User.objects.get(username=username)
table.seats.north = user
table.seats.save()
print(table.seats.north)
以上是 变化与一对一不节能 的全部内容, 来源链接: utcz.com/qa/261657.html