Django self-referential foreign key

前端 未结 4 780
渐次进展
渐次进展 2020-11-28 05:44

I\'m kind of new to webapps and database stuff in general so this might be a dumb question. I want to make a model (\"CategoryModel\") with a field that points to the primar

相关标签:
4条回答
  • 2020-11-28 06:20

    https://books.agiliq.com/projects/django-orm-cookbook/en/latest/self_fk.html

    class Employee(models.Model):
        manager = models.ForeignKey('self', on_delete=models.CASCADE)
    

    OR

    class Employee(models.Model):
        manager = models.ForeignKey("app.Employee", on_delete=models.CASCADE)
    

    https://stackabuse.com/recursive-model-relationships-in-django/

    0 讨论(0)
  • 2020-11-28 06:30

    You can use the string 'self' to indicate a self-reference.

    class CategoryModel(models.Model):
        parent = models.ForeignKey('self')
    

    https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey

    0 讨论(0)
  • 2020-11-28 06:35

    You can pass in the name of a model as a string to ForeignKey and it will do the right thing.

    So:

    parent = models.ForeignKey("CategoryModel")
    

    Or you can use the string "self"

    parent = models.ForeignKey("self")
    
    0 讨论(0)
  • 2020-11-28 06:40

    You also to sett null=True and blank=True

    class CategoryModel(models.Model):
        parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True)
    

    null=True, to allow in database
    blank=True, to allow in form validation

    0 讨论(0)
提交回复
热议问题