Reputation: 1230
I newbie with Django Framework and I wish to know if is possible I access a attribute from the model X via model Y...In my case a have a model called "Evaluation" this model receive the scores of evaluations of the candidates..they have a ForeignKey that receive the Candidate(what is another model) and a PositiveIntegerField with receive a score what I want is access this PositiveIntegerField via Candidate model, it's possible?
My models.py:
from django.db import models
from jsonfield import JSONField
from site_.settings import MEDIA_ROOT
from django.core.validators import MaxValueValidator
class Criterion(models.Model):
label = models.CharField(max_length=100)
def __str__(self):
return self.label
class Candidate(models.Model):
name = models.CharField(max_length=100)
e_mail = models.EmailField(max_length=100, default = '')
github = models.URLField(default = '')
linkedin = models.URLField(max_length=100, default = '')
cover_letter = models.TextField(default = '')
higher_education = models.BooleanField(default = False)
docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)
def __str__(self):
return self.name
class Evaluation(models.Model):
candidate = models.ForeignKey(Candidate)
criterion = models.ForeignKey(Criterion, default='')
score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
appraiser = models.ForeignKey('auth.User')
def __str__(self):
return str(self.candidate)
#model de teste
class Teste(models.Model):
nome = models.CharField(max_length=10)
def __str__(self):
return str(self.nome)
Upvotes: 0
Views: 3024
Reputation: 4092
You have a two solution to access the Evaluation objects
Example 1
candidateObj = Candidate.objects.get(id=your_candidate_id)
evaluationObjs = Evaluation.objects.filter(candidate=candidateObj)
Example 2
evaluationObjs = candidateObj.evaluation_set.all()
If you create only one Evaluation object then you directly use
score = candidateObj.evaluation_set.get().score
Hope this will help you
Upvotes: 1
Reputation: 1391
Like other answers, you use backwards relation in Django.
See example: Many-to-one relationships
And Examples of model relationship API
Upvotes: 1
Reputation: 20369
You can use
Candidate_obj.evaluation_set.all()[0].score
Since you are using a Foriegn Key
, there is chance to multiple Evaluation
objects.So Candidate_obj.evaluation_set.all()
may get more than one objects.
Upvotes: 0