How to pull a Foreignkey from the models on Django?

Asked

Viewed 110 times

1

Hello I am developing an application and I have a problem, if someone knows how to solve. I created the following models:

class Cliente(models.Model):

user = models.OneToOneField(User, on_delete=models.CASCADE)
nome = models.CharField(max_length=100, null=False)
email = models.EmailField(null=False)
senha = models.CharField('Senha',max_length=100, null=True)
celular = models.CharField(max_length=16, null=False)
data_nascimento = models.DateField(null=True)
photo = models.ImageField(upload_to='clients_photos', null= True, blank=True)


def __str__(self):
    return self.nome 

class Dieta(models.Model):
    nome = models.ForeignKey(Cliente, on_delete=models.CASCADE)
    periodo1 = models.CharField(max_length=100, null=True, blank=True)
    refeicao1 = models.TextField(null=True, blank=True)
    periodo2 = models.CharField(max_length=100, null=True, blank=True)
    refeicao2 = models.TextField(null=True, blank=True)

class Meta:
    db_table = 'Dieta'

def __str__(self):
    return str(self.nome) 

Now I want to pull this Diet to be displayed in html and I am unable to access its attributes, follows view class of this function:

def dieta(request):  
    dieta = Dieta.objects.all()
    return render(request, 'dieta.html', {'dieta' : dieta})
  • Please note that you are searching all diet records from the database, not just one. How are you accessing the diet variable in the template?

1 answer

1


Hello, to your variable dieta is a queryset that returns all diets registered in your database. If you want to take just one diet, it would be a case of passing some parameter in your method, something like:

def dieta(request, id):
    try:
        dieta = Dieta.objects.get(id=id)
    except ObjectDoesNotExist:
        # dispara alguma exceção

OR

If you want to display all diets in the template, your view continues as is, you would only change the name of the dieta for dietas and in the template you would do something like:

{% for dieta in dietas %}
   {{ dieta.nome }}
{% endfor %}

Within the iteration you have access to your class attributes.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.