How do I access the key value of a Django ForeignKey field without a table lookup?

时间:2017-04-06 17:17:11

标签: django django-models

I have several models in Django with ForeignKey fields that are linked to models with meaningful (non-generated) primary keys. How can I set or get the ForeignKey field of an instance of such a model without forcing a table lookup to retrieve the actual object that is pointed to? Here's an example:

class Country(models.Model):
    iso = models.CharField(
        max_length=2,
        primary=True)
    name = models.CharField(
        max_length=128,
        null=False,
        blank=False)

class Address(models.Model):
    street = models.CharField(max_length=64)
    city = models.CharField(max_length=64)
    country = models.ForeignKey(Country)

I'd like to be able to set an instance of the Address class' country field to 'US' and similarly, see that value ('US') without having to say address.country.iso and (presumably) force a table lookup. How do I do that?

1 个答案:

答案 0 :(得分:0)

address.country_id

更新:

address.country_id = 'UK'
address.save()

也许您需要强制更新:address.save(force_update=True)