Ken Ist
Ken Ist

Reputation: 79

OneToOne field in django default

Please help. I have a model:

class Book(core.BaseModel):
    book_link = models.OneToOneField('self',  default = "",  on_delete=models.CASCADE)
    book_name = models.CharField('Name', max_length=250)

I want to set 'self' in field book_link that will return in this field - book_name or Book Model object.

But when I create new Book object - Django shows me in column "book_link" all book names which I can choose and save new object. I want that when I created new object it will authomatically save for this object this name!

Upvotes: 0

Views: 325

Answers (1)

Sajad Rezvani
Sajad Rezvani

Reputation: 404

If I have understood your question, you want to create something like a linked list of books. To do so, first do not use one to one field unless each book is only and only linked to one book. To link one object to itself, you can use the name of model in string format.

And also note the way you had provided default was faulty, It is better to make it nullable with null=True.

My recommended model will be this:

class Book(models.Model):
    book_link = models.ForeignKey(to='Book', null=True,  on_delete=models.CASCADE, related_name="linked_books")
    book_name = models.CharField('Name', max_length=250)

Upvotes: 1

Related Questions