Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django,如何通过模型字段访问模型内部的模型_Python_Django_Django Models - Fatal编程技术网

Python Django,如何通过模型字段访问模型内部的模型

Python Django,如何通过模型字段访问模型内部的模型,python,django,django-models,Python,Django,Django Models,我有两个模型,它们之间有多对一的关系 from django.db import models class Continent(models.Model): name = models.CharField(max_length=255, unique=True) code = models.CharField(max_length=2, unique=True, primary_key=False) c = Continent.objects.get(id=1)

我有两个模型,它们之间有多对一的关系

from django.db import models


class Continent(models.Model):
    name = models.CharField(max_length=255, unique=True)
    code = models.CharField(max_length=2, unique=True, primary_key=False)
    c = Continent.objects.get(id=1)
    countries = c.country_set.all()
    class Meta:
        ordering = ["name"]


class Country(models.Model):
    name = models.CharField(max_length=255, unique=True)
    capital = models.CharField(max_length=255)
    code = models.CharField(max_length=2, unique=True, primary_key=False)
    continent = models.ForeignKey('Continent')
    population = models.PositiveIntegerField()
    area = PositiveIntegerField()
    class Meta:
        ordering = ["name"]
我希望可以通过大陆模型中的“国家”属性访问大陆的国家。我试图像文档(下面的链接)中那样“向后”跟踪关系,但无法使其工作。

您需要在
ForeignKey
关系中设置一个
相关的\u name
参数。这将自动向
大陆
模型添加具有该名称的字段

这就是您的模型的外观(请注意
Country.contraction
foreign key字段中的'related_name'参数):

现在您可以执行以下操作:

def test():
    c = Continent.objects.get(id=1)
    for country in c.countries.all():
        print(c.name)

country\u set
是用作相关名称的默认名称。您不需要在
类中将其设置为显式字段。它是在幕后创建的

def test():
    c = Continent.objects.get(id=1)
    for country in c.countries.all():
        print(c.name)