这是我与表单关联的代码:
# models
class Date(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=64, null=True)
class Photo(models.Model):
date = models.ForeignKey('Date', on_delete=models.CASCADE)
image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/')
# form
class DateForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = Date
exclude = ('user',)
# view
class CreateDateView(LoginRequiredMixin, CreateView):
template_name = 'app/date/form.html'
form_class = DateForm
def form_valid(self, form):
form.instance.user = self.request.user
form.save() # by the way why do I save this form? Is it okay to save it in form_valid method?
photos = self.request.FILES.getlist('image')
for photo in photos:
Photo.objects.create(image=photo)
return super().form_valid(form)问题是,如果照片对象需要Date模型id,则如何保存它。它会引发 NULL约束failed: app_photo.date_id,据我所知,我必须编写如下内容:
Photo.objects.create(date=date_from_the_form, image=photo)但是如何从日期模型中得到pk呢?希望你能理解我的问题,如果有任何问题可以毫不犹豫地写在下面的评论部分。提前感谢!
发布于 2022-05-12 16:36:07
您需要先创建date对象。另外,每一次约会都是独一无二的吗?如果是这样的话,您需要更改模型元声明以包含unique_together。
在创建每个对象时,还需要避免for循环。它非常昂贵,因为它将对每个调用的save()进行往返访问。这就是bulk_create的作用所在,它将数据库的触点限制为一个命令来创建多个对象。
这是伪码让你去:
if len(photos) > 0: # don't create a date if there aren't photos
date = Date() # add your arguments
filtered = Date.objects.filter(date=date)
date = date.create() if not filtered.exists() else date = filtered[0] # but this is potentially dangerous if you risk duplicate dates. Only use this if you know it's the correct date
photos = [Photo(date=date,image=p) for p in photos]
Photo.objects.bulk_create(photos)祝好运!
发布于 2022-05-13 08:15:10
您需要保存照片对象:
def form_valid(self, form):
form.instance.user = self.request.user
form.save() # by the way why do I save this form? Is it okay to save it in form_valid method?
photos = self.request.FILES.getlist('image')
for photo in photos:
temp = Photo.objects.create(image=photo)
temp.save()
return super().form_valid(form)https://stackoverflow.com/questions/72219034
复制相似问题