在Django中,递归关系和与未定义模型的关系有什么用?

时间:2021-02-20 20:18:22

Text below is from Django docs which provide

下面的文字来自提供的Django文档

To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey(’self’). If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself.

要创建递归关系 - 与自身具有多对一关系的对象 - 请使用models.ForeignKey('self')。如果需要在尚未定义的模型上创建关系,则可以使用模型的名称,而不是模型对象本身。

can someone give me an example of the usage of these capabilities in Django? Thanks

有人能给我一个在Django中使用这些功能的例子吗?谢谢

2 个解决方案

#1


3  

You can use it to create links to other objects of this Model.

您可以使用它来创建指向此模型的其他对象的链接。

For example if you have many members in a website and each has an inviter (also of Member type) you can do the following:

例如,如果您在网站中有许多成员,并且每个成员都有一个邀请者(也是成员类型),您可以执行以下操作:

class Member(Model):
    inviter = models.ForeignKey(
        'self',
        related_name="invited_set"
    )

If you want the inviter, you do:

如果你想要邀请者,你可以:

Member.objects.get(id__exact=5).inviter

If you want all members that this member has invited you use:

如果您希望此会员邀请的所有会员使用:

Member.objects.get(id__exact=5).invited_set

#2


1  

For models not yet defined:

对于尚未定义的模型:

class Gallery(models.Model):
    title_image = models.ForeignKey('Image')

class Image(models.Model):
    part_of = models.ForeignKey(Gallery)

since these classes refer to each other, at least one of them needs to refer to a class not yet defined.

由于这些类相互引用,因此至少其中一个需要引用尚未定义的类。

#1


3  

You can use it to create links to other objects of this Model.

您可以使用它来创建指向此模型的其他对象的链接。

For example if you have many members in a website and each has an inviter (also of Member type) you can do the following:

例如,如果您在网站中有许多成员,并且每个成员都有一个邀请者(也是成员类型),您可以执行以下操作:

class Member(Model):
    inviter = models.ForeignKey(
        'self',
        related_name="invited_set"
    )

If you want the inviter, you do:

如果你想要邀请者,你可以:

Member.objects.get(id__exact=5).inviter

If you want all members that this member has invited you use:

如果您希望此会员邀请的所有会员使用:

Member.objects.get(id__exact=5).invited_set

#2


1  

For models not yet defined:

对于尚未定义的模型:

class Gallery(models.Model):
    title_image = models.ForeignKey('Image')

class Image(models.Model):
    part_of = models.ForeignKey(Gallery)

since these classes refer to each other, at least one of them needs to refer to a class not yet defined.

由于这些类相互引用,因此至少其中一个需要引用尚未定义的类。