Changes to model with one to one relation not saving

时间:2017-12-18 08:12:16

标签: django django-models

I have two models that I'm relating using Django's OneToOneField, following this documentation: https://docs.djangoproject.com/en/2.0/topics/db/examples/one_to_one/

<style name="AccountSetting" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimaryDark">#ffffff</item>
    <item name="colorPrimary">#ffffff</item>
</style>

When I run this code I can successfully get the relationship working

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)

The print statement prints out the name of the player sitting north. But if I try to access the table again like this:

table = BridgeTable.objects.get(pk='1')
user = User.objects.get(username=username)
table.seats.north = user
table.seats.north.save()
print(table.seats.north)

I get "None" instead of the user's name. Is there something I'm missing, like a save that I missed or some concept I'm not understanding? Thanks.

1 个答案:

答案 0 :(得分:1)

您应该保存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)