views:

40

answers:

2

If I want to add a Foreignkey to a model from another class in the same model e.g.

class1 (models.Model):
    variable1 = models.IntegerField()
class2 (models.Model):
    variable2 = models.CharField()
    foreignkey = models.Foreignkey(class1.variable1)

Is that possible? Does that make sense as a programming move?

This ForeignKey would be an ID Number (like a primary key) that I would like to import to other classes as well.

@ Manoj Govindan:

e.g.

class author(models.Model):
    authorlabel= models.IntegerField() # With choices
    ...

class books(models.Model):
    books=models.CharField()
    foreignkey= models.Foreignkey(author.authorlabel)

So that I have that data available in that table(?)/model as well.

Thanks!

A: 

Perhaps this is what you are looking for:

models.ForeignKey(class1, to_field = 'variable1')

Relevant documentation is here.

This ForeignKey would be an ID Number (like a primary key) that I would like to import to other classes as well.

Not sure what you mean by this. Can you rephrase it and add an example?

Manoj Govindan
The "key" with keys is that they uniquely identify a tuple in the relation ("a row in the table"). So the *to_field* has to be **unique**.AFAIK you can't define compound keys as a to_field, but I haven't tried. Has anyone ever used unique_together and pass an Iterable as the to_field? The singular in the parameter name suggests you'll get an Exception.
CharString
A: 

Addition to Manoj Govindan's answer...

This ForeignKey would be an ID Number (like a primary key) that I would like to import to other classes as well.

No it do not have to be a number, it can be a string, a datetime value or something else... But it have to be unique.

FallenAngel
interesting. datetime could be a cool ID. Thanks for that..
MacPython