Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object

后端 未结 17 1002
名媛妹妹
名媛妹妹 2020-11-29 01:04

I\'ve models for Books, Chapters and Pages. They are all written by a User:

from django.db import models
         


        
17条回答
  •  一向
    一向 (楼主)
    2020-11-29 01:37

    I think you'd be happier with a simpler data model, also.

    Is it really true that a Page is in some Chapter but a different book?

    userMe = User( username="me" )
    userYou= User( username="you" )
    bookMyA = Book( userMe )
    bookYourB = Book( userYou )
    
    chapterA1 = Chapter( book= bookMyA, author=userYou ) # "me" owns the Book, "you" owns the chapter?
    
    chapterB2 = Chapter( book= bookYourB, author=userMe ) # "you" owns the book, "me" owns the chapter?
    
    page1 = Page( book= bookMyA, chapter= chapterB2, author=userMe ) # Book and Author aggree, chapter doesn't?
    

    It seems like your model is too complex.

    I think you'd be happier with something simpler. I'm just guessing at this, since I don't your know entire problem.

    class Book(models.Model)
        name = models.CharField(...)
    
    class Chapter(models.Model)
        name = models.CharField(...)
        book = models.ForeignKey(Book)
    
    class Page(models.Model)
        author = models.ForeignKey('auth.User')
        chapter = models.ForeignKey(Chapter)
    

    Each page has distinct authorship. Each chapter, then, has a collection of authors, as does the book. Now you can duplicate Book, Chapter and Pages, assigning the cloned Pages to the new Author.

    Indeed, you might want to have a many-to-many relationship between Page and Chapter, allowing you to have multiple copies of just the Page, without cloning book and Chapter.

提交回复
热议问题