Home > Net >  Django / OnetoMany relation within the same class
Django / OnetoMany relation within the same class

Time:05-06

Here is my models.py

class Scenes(models.Model):
    name = models.SlugField('Scene name', max_length=60,unique=True)
    record_date = models.DateTimeField('Scene date')

    manager = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        blank=True,
        null=True,
        on_delete=models.SET_NULL)
   
 description = models.TextField(blank=True)

    previous = models.OneToOneField(
        'self',
        blank=True,
        null=True,
        related_name='next',
        on_delete=models.SET_NULL
    )

I have started with one instance : Scene1

The problem is I want to have on to many choices and not one to one like explained below

enter image description here

Nevertheless, When I change to

previous = models.ManyToManyField(

Then I also get an error about on_delete :

TypeError: init() got an unexpected keyword argument 'on_delete'

What would be the best djangonic way ?

CodePudding user response:

As I understand, your requirements are:

  • One scene can have only one previous scene
  • One scene can have many next scenes

You are almost there. Instead of OneToOneField, use ForeignKey with self reference:

previous = models.ForeignKey('self', related_name='next', ...)
  • Related