Can I Make a foreignKey to same model in django?

前端 未结 2 511
谎友^
谎友^ 2020-12-13 05:35

Assume I have this model :

class Task(models.Model):
    title = models.CharField()

Now I would like that a task may be relates to another

2条回答
  •  余生分开走
    2020-12-13 06:11

    Yea you can do that, make the ForeignKey attribute a string:

    class Task(models.Model):
        title = models.CharField()
        relates_to = ForeignKey(to='Task')
    

    In depth, you can also cross reference an app's model by using the dot notation, e.g.

    class Task(models.Model):
        title = models.CharField()
        relates_to = ForeignKey(to='.Task')  # e.g. 'auth.User'
    

提交回复
热议问题