Python模型Foreignkey向后关系

2024-04-18 05:22:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要通过大陆模式的“国家”属性来拯救一个大陆的所有国家。我该怎么做? 谢谢。你知道吗

from django.db import models

class Continent(models.Model):
    name = models.CharField(max_length=255, unique = True)
    code = models.CharField(max_length=255, unique = True)
    allCountries = models.Manager()
    countries = ???

class Country(models.Model):
    name = models.CharField(max_length=255 )
    capital = models.CharField(max_length=255 )
    code = models.CharField(max_length=255, unique = True)
    population = models.PositiveIntegerField()
    area = models.PositiveIntegerField()
    continent = models.ForeignKey(Continent)

Tags: nametruemodelmodels模式code国家length
1条回答
网友
1楼 · 发布于 2024-04-18 05:22:29

要获得某个大陆的所有国家,您必须执行以下操作:

continent = Continent.objects.get(name='Europe')
countries = continent.country_set.all() # returns all countries from Europe

您不需要在“大陆”中添加“国家”字段

相关问题 更多 >