0

我有一个内联表单集,其中 extra=24 是一天中的几个小时。添加新条目和保存我没有任何问题

OreSommInlineFormSet = inlineformset_factory(FarmacoGiornaliero, OreSomministrazione, 
                                             form=OreForm,  fields=('ore','farmaco', 'quantita'), 
                                             extra=24, can_delete=False)        

myospite = Ospite.objects.filter(cognome=cognome).filter(nome=nome)[0]                 


if request.method == 'POST':                       


    form = GiornalieroForm(request.POST)
    formset = OreSommInlineFormSet(request.POST, prefix='formset')

    if form.is_valid() and formset.is_valid():                           


        giornaliero=form.save(commit=True)      

        for form in formset.forms:
            ora = form.save(commit=False)
            ora.farmaco = giornaliero
            ora.ospite = myospite               
            ora.save()                                    

我试图弄清楚如何编辑和保存表单集的数据。我有一个查询集,它返回 24 个 OreFarmaco 实例,它应该填充表单集,但带有 instance 关键字的表单集本身只能预见一个实例。

OreSommInlineFormSet = inlineformset_factory(FarmacoGiornaliero, OreSomministrazione, form=OreForm, fields=('ore', 'quantita'), extra=24, can_delete=False)

myospite = Ospite.objects.filter(cognome=cognome).filter(nome=nome)[0]

locfarmaco = Farmaco.objects.filter(farmaco=farmaco)[0]

giornaliero = FarmacoGiornaliero.objects.select_related() \
            .filter(ospite=myospite) \
            .filter(farmaco=locfarmaco)[0]

orefarmaco = OreSomministrazione.objects.select_related().filter(farmaco=giornaliero).filter(ospite=myospite)           

if request.method == "POST":                      

        form = GiornalieroForm(request.POST, instance=giornaliero)                     

        formset = OreSommInlineFormSet(request.POST, prefix='formset', instance=orefarmaco[0])


        if form.is_valid() and formset.is_valid():                                                             

            giornaliero=form.save(commit=True)   
            formset.save()   

谢谢你。

4

1 回答 1

0
//try to rewrite this codes it's complicated. Use get() instead
myospite = Ospite.objects.filter(cognome=cognome).filter(nome=nome)[0]
locfarmaco = Farmaco.objects.filter(farmaco=farmaco)[0]
giornaliero = FarmacoGiornaliero.objects.select_related() \
        .filter(ospite=myospite) \
        .filter(farmaco=locfarmaco)[0]
//

if request.method == "POST":                      
    form = GiornalieroForm(request.POST, instance=giornaliero)                     
    if form.is_valid():  
        gio = form.save(commit=True)                                                           
        formset = OreSommInlineFormSet(request.POST, instance=gio)
        if formset.is_valid()
            gio.save()   
            formset.save() 
于 2013-02-28T15:46:01.483 回答