Django模型递归关系 [英] Django model recursive relationship

查看:176
本文介绍了Django模型递归关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 为什么要创建递归关系?
  1. Why would I create a recursive relationship?

    aField = models.ForeignKey('self')

  • 与上述相同吗?
  • Is this the same with the above?
  • 
            class aClass(models.Model):  
            aField = models.ForeignKey('aClass')
    

    推荐答案

    1. 当您希望具有相同模型结构的父节点和子节点时,可能需要创建一个递归关系.例如,如果您有带有文本,数据和user_id的注释:

    1. You may need to create a recursive relationship when you would like to have parent and child nodes with identical model structure. For example if you have comments with text, data and user_id:

    class Comment( models.Model ):
        text = models.TextField()
        create_date_time = models.DateTimeField()
        parent_comment = models.ForeignKey( 'self' )
    

  • 我认为是的(您可以尝试对其进行测试),但这不是一个很好的形式.如果更改类名,则必须更改括号中的字符串值.如果您使用自我",就不会感到头疼.

  • I think yes (you can try to test it) but it's not a good form. If you change a class name then you must change the string value in brackets. If you use 'self' you haven't this headache.

    这篇关于Django模型递归关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆