Q:

Django Retrieve id and name based on a ForeignKey

I have the following models :
class Projects(models.Model):
    id = models.IntegerField(primary_key=True, blank=True)
    name = models.CharField(max_length=20, unique=True)
    company = models.CharField(max_length=20, blank=True, null=True)
    creation_date = models.DateField(auto_now_add=True, auto_now=False)

class Packages(models.Model):
    id = models.IntegerField(primary_key=True, blank=True)
    name = models.CharField(max_length=50)
    extension = models.CharField(max_length=3)
    gen_date = models.DateTimeField(auto_now_add=True, auto_now=False)
    project = models.ForeignKey(Projects)

In my views, for the Homepage function, I'm trying to display the last package, AND the associated project.  I don't understand how to retrieve the 'project' field (FK) : 
try:
    lastpackages = Packages.objects.reverse()[:1].get()
except Packages.DoesNotExist:
    lastpackages = None

projectid = lastpackages.select_related('project_id')
project = Projects.objects.get(id=lastpackages.project)

return render(request, 'homepage.html', {'lastpackages': lastpackages,
                                         'project': project})

In fact, I want to display the 'projectname' corresponding to the package retrieved by reverse.  But the lines projectid and project are not correct. I hope it's enough clear.. 

A:

Sorry to say but your code is a bit messy. You don't need to look up the Project separately, django ORM does it for you:
package = Package.objects.order_by('-id')[0]
project = package.project

package.project would give you the project associated with the package, no need to query using id.
Some advises here:

You don't need to define id, django will do it for you.
Don't use plural form in your model name, django will do it for you.
In view it's usually good exercise to use get_object_or_404 to get the object, it saves your try except block.
reverse() should be used along with order_by() statement. In your case it's easier to just use id to find the last entry, because in django id is auto incremented.

