【问题标题】:django-orm : How to update one-to-one relation field valuedjango-orm:如何更新一对一的关系字段值
【发布时间】:2016-08-06 20:51:03
【问题描述】:

models.py

class Area(models.Model):
    area_name = models.CharField(max_length=255, null=False, blank=False)
    description = models.TextField(null=False, blank=False)

class AreaPoint(models.Model):
    x_axis = models.FloatField(default=0.0)
    y_axis = models.FloatField(default=0.0)
    area = models.OneToOneField(Area,primary_key=True,on_delete=models.CASCADE)

我尝试了两种方法,但都失败了,请指导我。谢谢

# first method : 
# Area.objects.filter(id=304).update(area_name="today is 1", description="today is 1", areapoint__x_axis=111,areapoint__y_axis=222)
# error : Area has no field named 'areapoint__y_axis'

# second method : 
obj = Area.objects.get(id=304)
print obj.areapoint.x_axis # 277
print obj.areapoint.y_axis # 65
obj.areapoint.x_axis = 100
obj.areapoint.y_axis = 200
print obj.areapoint.x_axis # 100
print obj.areapoint.y_axis # 200
obj.save()
print obj.areapoint.x_axis # 100
print obj.areapoint.y_axis # 200

第二种方法很奇怪。
areapoint.x_axisareapoint.y_axis更新后真的不一样了。 但在我的数据库中。它还是一样的。

【问题讨论】:

  • 您不需要保存areapoint 而不是obj 吗?即obj.areapoint.save()

标签: python django django-orm


【解决方案1】:

在这两种方法中,您都在尝试更新 Area 对象而不是 AreaPoint 对象。

以下是使用这两种方法的方法:

第一种方法:使用update方法:

# here is what you are doing:
Area.objects.filter(id=304).update(area_name="today is 1",
                                   description="today is 1",
                                   areapoint__x_axis=111,
                                   areapoint__y_axis=222)

上面将返回Area 的对象,并且由于没有字段areapoint__x_axis 等,因此会引发错误。

您可以做的是过滤AreaPoint 并更新它:

AreaPoint.objects.filter(area_id=304).update(x_axis=111, y_axis=222)

第二种方法:

obj = Area.objects.get(id=304)
obj.areapoint.x_axis = 100
obj.areapoint.y_axis = 200 

# save obj.areapoint instead
obj.areapoint.save()

第三种方法:

areapoint = AreaPoint.objects.get(area_id=304)
areapoint.x_axis = 100
areapoint.y_axis = 200
areapoint.save()

【讨论】:

    猜你喜欢
    • 2013-09-29
    • 1970-01-01
    • 2014-02-23
    • 2017-07-18
    • 2012-12-01
    • 2015-12-02
    • 1970-01-01
    • 2015-03-24
    • 2019-07-06
    相关资源
    最近更新 更多