Having issue returning data in django templates

So I am working on a small django project and I am having an issue with a foreign key. I have a model with 2 tables mymodel1 and mymodel2.

#Models.py
class Mymodel1(moels.Model):
  name = models.CharField(max_length=20)
  blurb = models.CharField(max_length=20)
  created = models.DateTimeField(auto_now_add=True)
  updated = models.DateTimeField(auto_now=True)
  
 class Mymodel2(moels.Model):
  name = models.ForeignKey(Mymdoel1, on_delete=models.CASCADE)
  somethingelse = models.CharField(max_length=20)

my urls pass in the id from Mymodel1 and my template returns the data but I also want the template to return the data from my model2

def get_details(request ,id):
if User.is_authenticated:
    try:
        single_record = Mymodle1.objects.get(id=id)
        details = Mymodel2.objects.get(id=single_record.name)
    except Exception as e:
        raise e
    context = {
        'single_asset': single_asset,
        'details': details,
    }
    return render(request, 'detail.html', context=context)
else:
    return render(request, 'home.html')

but I cannot get the view to return the details.

As we noted from comments, you were not calling your details query correctly here:

details = Mymodel2.objects.get(id=single_record.name)

The reason was because you were querying the id of the model (which in almost every case is a number, int, big int, etc...) with the attribute of the record's name. I.e. id=single_record.name this cannot work.

To fix this you can look at your modelFK relationship names for the attributes between Mymodel1 and Mymodel2. In that instance if you call your posted single_record you can see:

single_record = Mymodle1.objects.get(id=id)

Since Mymodel1 has the attr name in Mymodel2 for the FK relationship you would find them by altering your details query to this:

details = Mymodel2.objects.get(name=single_record)

Or if you want to use id (assuming your pk is named id):

details = Mymodel2.objects.get(name__id=single_record.pk)

Or you can use the reverse relationship for Mymodel1 to Mymodel2. Django, by default gives you a default related_name as the ModelName, in lower, followed by _set, so since you have no related name you can do:

details = single_record.mymodel2_set.all()

Back to Top