tags:

views:

73

answers:

2

hi,

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

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

Thanks John

A: 

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

foo.fk_field = bar.fk_field
Hank Gay
I guess this would change the foreign key data from one model to another. I want to copy it so that foo and bar would both have the same foreign key data (a duplicate copy of the same data and not actually the same record)
John
+1  A: 

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 usefull to you. ^^

Jayme
This isn't an answer. Please delete and repost as a comment.
Daniel Roseman
added example. hope this helps
John