2010-05-12 74 views
1

如何將外鍵數據從一個對象複製到另一個對象?django將外鍵數據複製到另一個模型

例如

#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') 

我現在想給d一樣的外鍵數據。即記錄b和c。

感謝 約翰

回答

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) 

我認爲這是完成的。但我不知道,我希望它對你有用。 ^^

+0

這不是一個答案。請刪除並重新發布評論。 – 2010-05-12 18:41:14

+0

增加了一個例子。希望這可以幫助 – John 2010-05-13 09:17:09

0

我不清楚究竟上你問。我假設它是超過

foo.fk_field = bar.fk_field 
+0

我想這會將外鍵數據從一個模型更改爲另一個模型。我想複製它,以便foo和bar都具有相同的外鍵數據(相同數據的重複副本,而不是實際上相同的記錄) – John 2010-05-13 08:16:05

相關問題