Ayoub Bsl
Ayoub Bsl

Reputation: 159

get foreign key from model

I want to get pk from model.

model.py

class Produit(models.Model):
    ref=models.CharField(max_length=100, default='',primary_key=True)
    marq=models.CharField(max_length=100, default='')
    nomp=models.CharField(max_length=100, default='')
    qte = models.IntegerField(default=0)
    codecateg=models.ForeignKey(categorie, on_delete=models.CASCADE)

class categorie(models.Model):
    codecateg=models.CharField(max_length=100, default='' , primary_key=True)
    nomcat=models.CharField(max_length=30, default='' ) 

views.py

def edit_prod(request , id = None):
    ins = get_object_or_404(Produit,ref=id)
    datedit = {'ins': ins}
    return render(request, 'produit/modal_prode.html',datedit )

When I want to get ins.codecateg I get categorie object.

Upvotes: 0

Views: 65

Answers (2)

Bijoy
Bijoy

Reputation: 1131

In 'produit/modal_prode.html' you are sending Produit object, so ins is the object, and when you do ins.codecateg it will get the categorie object associated with it, but if you wnat to get the categorie pk you would have to

<h4>{{ ins.codecateg.pk }}</h4>

in html.

Upvotes: 1

zhiyu cao
zhiyu cao

Reputation: 66

if what you want is pk

ins.codecateg.pk

Upvotes: 1

Related Questions