Django Model ForeignKey 2
I dont understand how I can "import"(I dont know the right terminology, so please dont crucify me on this) a Foreignkey from 1 model class to a another:
e.g.
class1 (models.Model):
variable1 = models.CharField()
variable2 = models.CharField()
class2 (models.Model):
variable3 = models.CharField()
variab开发者_运维技巧le4 = class1.variable1 "imported" from class1
So now I have all the data from variable1 from class1 available in class2.
I assume this would be accomplished by a ForeignKey.
If I take the example of the official Django documentation (see below), I dont get my answer because:
Why does it only mention the other model and not the variable I create from it.
This would be for a future model, where I dont know the fields yet. But i know the fields already. Again no variable, just the model.
This would be what I am looking for. But this is "imported" from another app. But with me it is in the same app.
ad 1.
class ForeignKey(othermodel[, **options])¶
ad 2.
class Car(models.Model):
manufacturer = models.ForeignKey('Manufacturer')
# ...
class Manufacturer(models.Model):
# ...
ad 3.
class Car(models.Model):
manufacturer = models.ForeignKey('production.Manufacturer')
Thanks!
If I understand your question correctly.
You are establishing the relationship to the whole model with a foreign key, not just one field, so you will have access to all the fields, even if you only want one.
variable4 = models.ForeignKey(class1)
now you can say variable4.variable1 or variable4__variable2 in a queryset.
Re point 2 - use variable4 = models.ForeignKey('class1') if class1 not already defined Re point 3 - no need to add application if model in the current application.
精彩评论