好吧,如果我明白你想要什麼。 你必須修改你的模型:
#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)
我認爲這是完成的。但我不知道,我希望它對你有用。 ^^
這不是一個答案。請刪除並重新發布評論。 – 2010-05-12 18:41:14
增加了一個例子。希望這可以幫助 – John 2010-05-13 09:17:09