同时编辑主题及其子条目

时间:2018-12-14 23:50:51

标签: django forms model instance edit

我要同时编辑一个条目,它是子条目。

因此,我有一个价格模型,该模型具有Entry(另一个模型)作为外键。

class Price(models.Model):
    price = models.ForeignKey(Entry, on_delete = models.CASCADE)
    ptext = models.FloatField(blank = True, null = True) 
    date_added = models.DateTimeField(auto_now_add = True)

    class Meta:
        verbose_name_plural = 'prices'

    def __str__(self):
        return self.ptext[:50] + "..."  `

我如何从入门模型中提取价格?

我只能修改输入模型中的数据,而不能修改价格模型。实例部分特别给了一个问题。我不知道要为PriceForm实例放置什么。

def edit_entry(request, entry_id):
   entry = Entry.objects.get(id = entry_id)
   price = entry.price_set.get.all() 
   topic = entry.topic

   check_topic_owner(topic.owner, request.user)  


   if request.method != 'POST':

      form = EntryForm(instance = entry)
      form2 = PriceForm(instance = price) 

   else: 

      form = EntryForm(instance=entry, data = request.POST)
      form2 = PriceForm(instance=price, data = request.POST)

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

        form.save() 
        form2.save() 

        return HttpResponseRedirect(reverse('learning_logs:topics'))



    context = {'entry': entry, 'topic': topic, 'form': form, 'form2':form2}

    return render(request, 'learning_logs/edit_entry.html', context)

1 个答案:

答案 0 :(得分:1)

要从 entry 对象中获取所有 price 对象,应使用

price = entry.price_set.all()

代替

price = entry.price_set.get.all()