Limit Django's inlineformset_factory to only create new objects

前端 未结 3 1140
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 13:41

I am using django\'s inline formset factory. To use the example in the docs,

author = Author.objects.get(pk=1)
BookFormSet = inlineformset_factory(Author, Book)         


        
3条回答
  •  时光取名叫无心
    2021-02-04 14:09

    inlineformset_factory takes a formset kwarg, which defaults to BaseInlineFormSet. BaseInlineFormSet subclasses BaseModelFormSet, which defines a get_queryset method. If you create a BaseInlineFormSet subclass and override get_queryset to return EmptyQuerySet(), you should get what you're after. In the above example then, it would look like this:

    from django.db.models.query import EmptyQuerySet
    from django.forms.models import BaseInlineFormSet
    
    class BaseInlineAddOnlyFormSet(BaseInlineFormSet):
        def get_queryset(self):
            return EmptyQuerySet()
    
    author = Author.objects.get(pk=1)
    BookFormSet = inlineformset_factory(Author, Book, formset=BaseInlineAddOnlyFormSet)
    formset = BookFormSet(request.POST, instance=author)
    

提交回复
热议问题