我正在尝试为here中看到的数据复制数据方案。每次发射都有一个带有单个垫的位置,当前定义我的模型,如下所示:
class Location(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255, blank=True, default="")
country_code = models.CharField(max_length=255, blank=True, default="")
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Location'
verbose_name_plural = 'Locations'
class Pad(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255, blank=True, default="")
info_url = models.URLField(blank=True, null=True)
wiki_url = models.URLField(blank=True, null=True)
map_url = models.URLField(blank=True, null=True)
location = models.ForeignKey(Location, related_name="pads", blank=True, on_delete=models.CASCADE)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Pad'
verbose_name_plural = 'Pads'
如果我从Django外壳查询启动,或者如果我使用Django Restframework序列化(seen here)启动,它将所有护垫拉到某个位置,而不是 一个单独的发射台。
示例:
"location": {
"id": 16,
"name": "Cape Canaveral, FL, USA",
"country_code": "USA",
"pads": [
{
"id": 62,
"name": "Space Launch Complex 37B, Cape Canaveral, FL",
"info_url": null,
"wiki_url": "https://en.wikipedia.org/wiki/Cape_Canaveral_Air_Force_Station_Space_Launch_Complex_37",
"map_url": "http://maps.google.com/maps?q=28.531700,-80.564950"
},
{
"id": 84,
"name": "Space Launch Complex 40, Cape Canaveral, FL",
"info_url": "",
"wiki_url": "https://en.wikipedia.org/wiki/Cape_Canaveral_Air_Force_Station_Space_Launch_Complex_40",
"map_url": "http://maps.google.com/maps?q=28.56194122,-80.57735736"
}
]
如何获取关系以正确地仅显示分配给发射的一个打击垫,而不是返回某个位置的所有可能的打击垫,以便我的实现与第一个链接中所示的原始功能相匹配?
编辑:
好了,现在数据以正确的格式存储在数据库中了,如外壳程序所示,启动在某个位置有一个垫子。剩下的问题是如何序列化它以使其完全像原始数据源一样返回,即使用launch-> location-> single-pad:
>>> launch = Launch.objects.first()
>>> launch
<Launch: Falcon Heavy | STP-2>
>>> launch.pad
<Pad: Launch Complex 39A, Kennedy Space Center, FL>
>>> launch.pad.location
<Location: Kennedy Space Center, FL, USA>
>>> launch.pad.location.pad.all()
<QuerySet [<Pad: Launch Complex 39A, Kennedy Space Center, FL>, <Pad: Launch Complex 39B, Kennedy Space Center, FL>]>