user2361174
user2361174

Reputation: 1942

Django model has no foreign key object set

So I'm making django models of Country and Embassy, an Embassy requires two countries to be involved, one country that represents the Embassy, and another one that the Embassy is located in. So I've put two Countrys as foreign keys in Embassy Here's my models.py:

from django.db import models

class Country(models.Model):
    code = models.CharField(primary_key=True, max_length=3) #ISO Alpha-3 Country Code
    name = models.CharField(max_length=50, db_column="Name")

    def __str__(self):
        return self.name


class Embassy(models.Model):
    government = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="government")
    location = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="location")
    name = models.CharField(max_length=200, db_column="Name")
    street_address = models.CharField(max_length=200, db_column="Address")
    city = models.CharField(max_length=50, db_column="City")
    phone_number = models.IntegerField(default=-1, db_column="Phone Number")
    fax_number = models.IntegerField(null=True, blank=True, db_column="Fax Number")
    email_address = models.CharField(max_length=200, db_column="Email")
    website = models.CharField(max_length=200, db_column="Link")

    def __str__(self):
        return self.name

Now when I go into the shell I want to find what embassies are associated with a country:

>>> from appName.models import Country, Embassy
>>> c = Country(code="USA", name="United States of America")
>>> c.save()
>>> Country.objects.all()
<QuerySet [<Country: United States of America>]>
>>> c.embassy_set.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Country' object has no attribute 'embassy_set'

When looking over the django tutorial with the Choice model having a foreign key of the Question model, the question objects have an attribute that is a set of choice objects (q.choice_set.all() returns a QuerySet). However my Country objects do not have an Embassy object set as an attribute. Why is this happening? How can I fix this?

Upvotes: 1

Views: 2438

Answers (1)

Evans Murithi
Evans Murithi

Reputation: 3257

This is because you have already given a related_name where you have referenced the Country model. Also Country is being referenced by two fields in the Embassy model. With related name, you can do:

c.government.all()

This will return all Embassy to which the Country c is the government.

c.location.all()

Will return all Embassy that reside in the Country c.

Reference: Backward relationships

Upvotes: 4

Related Questions