开发者

django copy foreign key data to another model

how can i copy foreign key data from one object to another?

e.g.

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

class ModelB(models.Model)
   field2 = models.CharField(max_length=1开发者_开发百科0)
   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')

I now want to give d the same foreign key data as a. i.e. records b and c.

Thanks John


Well, if I understood what you want. You'll have to modify your model to:

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

So, you can do:

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

Or, if you prefer to keep your model you can do:

#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

Another way I think it can be what you want is:

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

I think it's done. But I don't know, I hope it could be useful to you. ^^


I'm not clear on exactly what you're asking. I'm assuming it's something more than

foo.fk_field = bar.fk_field
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜