Reputation: 825
I have two models:
class FirstModel(models.Model):
foo = models.IntegerField(default=0)
class SecondModel(models.Model):
bar = models.OneToOneField(FirstModel, on_delete=models.CASCADE, primary_key=True)
How do I make a variable baz
that is from FirstModel.foo
?
I wish it was as easy as:
class SecondModel(models.Model):
bar = models.OneToOneField(FirstModel, on_delete=models.CASCADE, primary_key=True)
baz = bar.foo
Ultimate Goal: To get foo
from an instance of SecondModel
like second_model_instace.foo
.
Upvotes: 1
Views: 1141
Reputation: 4170
You can use related_name
in the linking model for backward reference:
class FirstModel(models.Model):
foo = models.IntegerField(default=0)
class SecondModel(models.Model):
bar = models.OneToOneField(
FirstModel,
related_name='baz',
on_delete=models.CASCADE,
primary_key=True
)
Now you can access as first_model_intance.baz
if the link exists else you will get DoesNotExsist
exception. The default is:
If you do not specify the related_name argument for the OneToOneField, Django will use the lower-case name of the current model as default value.
Update:
If you want to get second_model_instace.foo
, you do not even need related_name
(backward reference). It is forward reference, which is already explicit. First get the first_model (via OneToOne Field) and then its attribute foo
, that is:
second_model_instance.bar.foo
Upvotes: 3