16shells
16shells

Reputation: 106

Django views query and the foreign key lookup

I'm having trouble running a Django query (v1.9) within my views page. I'm basically retrieving one record from the primers table (that's working fine), then trying to retrieve the corresponding record from the 'gene' table:

models.py:

class Gene(models.Model):
    GeneName = models.CharField(max_length=10, unique=True)
    ChromosomeNo = models.CharField(max_length=2)

class Primer(models.Model):
    PrimerName = models.CharField(max_length=20, unique=True)
    Gene = models.ForeignKey(Gene)

views.py

def PrimerDetail(request, pk):
    primer_info = get_object_or_404(Primer, pk=pk)
    Gene_info = Gene.objects.get(Gene_id = primer_info.GeneName)

The problem appears to be with my use of primer_info.GeneName. I get:

'Primer' object has no attribute 'GeneName'

Change it to primer_info.Gene and I get:

Cannot resolve keyword 'Gene_id' into field. Choices are: ChromosomeLoc, ChromosomeNo, Comments, Disease, Disease_id, GeneName, NoExons, id, primer`

I can substitute for a string value and it works fine. How should I reference a field that is a foreign key object in this context?

Upvotes: 1

Views: 579

Answers (2)

Chitrank Dixit
Chitrank Dixit

Reputation: 4051

with the above description you can try out one more way of getting the Gene object this is follows as.

Gene_info = Gene.objects.get(pk = primer_info.Gene.id)

this would give you the object of Gene object that is foreign key in the Primer Table.

Upvotes: 1

Shang Wang
Shang Wang

Reputation: 25539

Well it's because you never have a field called Gene_id in your Primer model. Since Gene is the foreign key in Primer, it's easy to get Gene_info:

Gene_info = primer_info.Gene

If you want to query directly on Gene model(which is pretty unnecessary in your case), do:

Gene_info = Gene.objects.get(primer__id=primer_info.id)

Upvotes: 0

Related Questions