Django: Saving Model Models with Many-to-Many User Models

I have a Publicationand Authors. Since the issue of ordering Authormatters (the professor does not want to be included after the trainee who contributed some trivial data), I defined a many-to-many user model:

class Authorship(models.Model):
    author = models.ForeignKey("Author")
    publication = models.ForeignKey("Publication")
    ordering = models.IntegerField(default=0)

class Author(models.Model):
    name = models.CharField(max_length=100)

class Publication(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author, through=Authorship)

I have ModelFormto publish and use it in a view. The problem is that when invoked, form.save()authors are obviously added with the default order 0. I wrote a OrderedModelMultipleChoiceFieldwith a method cleanthat returns objects that will be stored in the correct order, but I did not find a hook where the m2m data is actually stored so that I can add / edit / delete instances Authorship.

Any ideas?

+3
2

M2M through, , , . , , :

...
publication = form.save()
#assuming that these records are in order! They may not be
order_idx = 0
for author in request.POST.getlist('authors'): 
    authorship = Authorship(author=author, publication=publication, ordering=order_idx)
    authorship.save()
    order_idx += 1

ModelForm save.

+2

, , - :

form = PublicationForm(...)
pub = form.save(commit=False)
pub.save()
form.save_m2m()

, . . .

+1

Source: https://habr.com/ru/post/1771547/


All Articles