双向一对多django

Bidirectional one-to-may django

我想在 django 中创建双向一对多和多对一关系,例如:

class User(models.Model):
   device = dont_know_what_to_write()

class Device(models.Model):
   user = models.ForeignKey(
     User,
     on_delete = models.CASCADE
   )

我该怎么办?

在 Django 中如果你定义一个从 AB 的关系,那么 Django 会自动添加一个 conceptualBA 的关系,您可以查询。因此 Django 已经反向添加了关系。实际上,如果您使用以下方法实现模型:

class User(models.Model):
    # no device
    pass

class Device(models.Model):
    user = models.ForeignKey(
        User,
        on_delete = models.CASCADE
   )

然后您可以访问与用户相关的设备集:

myuser<strong>.device_set.all()</strong>

这是一个 QuerySet,它将包含具有 myuser 作为 user 的所有 Device

您可以使用 related_name=… parameter [Django-doc]:

指定另一个名称
class Device(models.Model):
    user = models.ForeignKey(
        User,
        on_delete = models.CASCADE,
        <strong>related_name='devices'</strong>
    )

那么您可以通过以下方式获取设备:

myuser.<strong>devices</strong>.all()

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.