Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django / OnetoMany relation within the same class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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', ...)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading