django将外键数据复制到另一个模型

时间:2010-05-12 15:37:03

标签: django

如何将外键数据从一个对象复制到另一个对象?

e.g。

#models.py
class ModelA(models.Model)
   field1 = models.CharField(max_length=10)

class ModelB(models.Model)
   field2 = models.CharField(max_length=10)
   field3 = models.ForeignKey(ModelA)

#views.py
a = ModelA(field1 = 'hello')
b = ModelB(field2 = 'goodbye', field3 = a)
c = ModelB(field2 = 'goodbye again', field3 = a)

d = ModelA(field1 = 'another')

我现在想要给出与之相同的外键数据。即记录b和c。

由于 约翰

2 个答案:

答案 0 :(得分:1)

好吧,如果我明白你想要什么。 您必须将模型修改为:

#models.py
class ModelA(models.Model)
   field1 = models.CharField(max_length=10)
   field2 = models.ForeignKey(ModelA)

class ModelB(models.Model)
   field3 = models.CharField(max_length=10)

所以,你可以这样做:

#views.py
b = ModelB(field3 = 'goodbye')
c = ModelB(field3 = 'goodbye again')
a = ModelA(field1 = 'hello', field2 = [b, c])

d = ModelA(field1 = 'another', field2 = a.field2)

或者,如果您希望保留模型,则可以执行以下操作:

#models.py
class ModelA(models.Model)
   field1 = models.CharField(max_length=10)

class ModelB(models.Model)
   field2 = models.CharField(max_length=10)
   field3 = models.ForeignKey(ModelA)

#views.py
a = ModelA(field1 = 'hello')
b = ModelB(field2 = 'goodbye', field3 = a)
c = ModelB(field2 = 'goodbye again', field3 = a)


d = ModelA(field1 = 'another')


#here you get all the objects related to "a"
query = ModelB.objects.filter(field3=a)

#iterated over them 
for obj in query:
    obj.field3 = d

另一种我认为可能是你想要的方式是:

#models.py
class ModelA(models.Model)
   field1 = models.CharField(max_length=10)
   field2 = models.ForeignKey(ModelA)

class ModelB(models.Model)
   field3 = models.CharField(max_length=10)
   field4 = models.ForeignKey(ModelA)

#views.py
a = ModelA(field1 = 'hello')
b = ModelB(field3 = 'goodbye', field4 = a)
c = ModelB(field3 = 'goodbye again', field4 = a)


d = ModelA(field1 = 'another', field2 = a)

我认为已经完成了。但我不知道,我希望它对你有用。 ^^

答案 1 :(得分:0)

我不清楚你究竟在问什么。我假设它不仅仅是

foo.fk_field = bar.fk_field