【问题标题】:Django reverse ForeignKey lookup returns NoneDjango 反向 ForeignKey 查找返回 None
【发布时间】:2023-03-16 22:49:02
【问题描述】:

我是 Django 开发新手,刚刚开始编写应用程序。 我在 models.py 中定义了两个类:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class NEO(models.Model):
    name        = models.CharField(max_length=100, default=' ')
    sighter     = models.ForeignKey(User, blank=True, null=True)
    date_sighted    = models.DateTimeField(default=timezone.now())
    ratings     = models.IntegerField(default=0)
    #coords     = models.ForeignKey('Coords', default='')

    def __unicode__(self):
        return self.name

class Coords(models.Model):
    ra      = models.FloatField('Right Ascension', default=0)
    dec     = models.FloatField('Declination', default=0)
    neo     = models.ForeignKey(NEO, related_name='neo_coords', null=True)

    def __unicode__(self):
        return str(self.ra) + ' ' + str(self.dec)

每个Coords 对象都链接到一个NEO,反之亦然。 取消注释Neo.Coords 行,然后调用n.Coords 将返回None。给定一个NEO对象,如何获取对应的Coords对象?

【问题讨论】:

  • 一个问题:我应该使用 OneToOne 吗?
  • 是的,如果一个neo 对象只能与一个coords 对象有关系。

标签: django django-models python-2.7


【解决方案1】:

让两个表使用双外键相互引用是没有意义的,因为您会遇到鸡或蛋的问题。您需要决定是否可以存在一对多关系或一对一关系。

一个NEO 可以有多个Coords 吗? Coord 可以有多个 NEOs 吗?如果答案是肯定的,那么您需要一个ForeignKeyForeignKey 应该在关系的许多 one-to-many 一侧。如果答案是否定的,并且只能是一对一的链接,那么您需要OneToOneField

访问reverse side of the relationship很简单:

# multiple coords per neo

class NEO(models.Model):
    name = ...

class Coords(models.Model):
    name = ...
    neo = models.ForeignKey(NEO)

c = Coords.objects.get(id=1)
c.neo # shows the neo

n = NEO.objects.get(id=1)
coords = n.coords_set.all() # multiple coords per neo

如果你有一对一的关系:

class NEO(models.Model):
    name = ...

class Coords(models.Model):
    name = ...
    neo = models.OneToOneField(NEO)

c = Coords.objects.get(id=1)
c.neo # shows the neo

n = NEO.objects.get(id=1)
coords = n.coords # only one possible coord per neo

https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

【讨论】:

  • 尝试 n.coords 返回“AttributeError: 'NEO' object has no attribute 'coords'”。
【解决方案2】:

这里的外键是多对一关系(as suggested in the docs),因此在您的情况下,多个Coords 对象可以绑定到单个NEO 对象。如果您想要 OneToOne 关系,您可能需要使用 models.OneToOneField (documentation here)。

在外键查找的情况下,您可以使用。

NEO.coords_set.get(**lookup_arguments_here)
# Here NEO.coords_set is the list of coords objects bound to this particular NEO object.

如果是OneToOne,您可以简单地使用

NEO.coords

【讨论】:

    猜你喜欢
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 2023-03-08
    • 1970-01-01
    • 2022-01-22
    • 2011-10-01
    • 2014-02-16
    相关资源
    最近更新 更多