Django-一次更新多个对象

时间:2020-07-27 06:08:14

标签: django django-models django-forms django-views django-templates

我有带有外键Blank的{​​{1}}模型。从Branch模型创建对象时,它们没有Blank。在另一个窗口中,我有共享按钮,通过该按钮我应在给定的数字范围内将Branch分配给这些Branch对象。例如,必须更新数字从1到3的空白分支。但是我不知道我应该在哪里以及如何实现更新过程。这是我的代码:

Blank

views.py

def blanks(request): if request.method == 'POST' and 'create-blank' in request.POST: form = CreateBlankForm(request.POST) if form.is_valid(): form.save() else: form = CreateBlankForm() blank_list = Blank.objects.all().order_by('-created') # Realize pagination paginator = Paginator(blank_list, 5) page = request.GET.get('page', 1) try: blanks = paginator.page(page) except PageNotAnInteger: blanks = paginator.page(1) except EmptyPage: blanks = paginator.page(paginator.num_pages) context = { 'form': form, 'blanks': blanks, } return render(request, 'blank.html', context)

models.py

class Blank(models.Model): blank_series = models.CharField(max_length=3) blank_number = models.IntegerField(blank=True, null=True) shared = models.DateField(blank=True, null=True) branch = models.ForeignKey(Branch, on_delete=models.CASCADE, blank=True, null=True) number_from = models.IntegerField() number_to = models.IntegerField() def __str__(self): return self.blank_series

forms.py

class CreateBlankForm(ModelForm): def save(self, commit=False): blank = super(CreateBlankForm, self).save(commit=False) number_of_objects = range(blank.number_from, blank.number_to+1) for i in number_of_objects: Blank.objects.create( blank_series = blank.blank_series, blank_number = i, shared = blank.shared, branch=blank.branch, number_from = blank.number_from, number_to = blank.number_to )

blanks.html

1 个答案:

答案 0 :(得分:0)

您可以覆盖Blank模型的save()函数,或添加signal中的post_save来调整分支

节省更多 models.py:

class Blank(models.Model):
    blank_series = models.CharField(max_length=3)
    blank_number = models.IntegerField(blank=True, null=True)
    shared = models.DateField(blank=True, null=True)
    branch = models.ForeignKey(Branch, on_delete=models.CASCADE, blank=True, null=True)

    number_from = models.IntegerField()
    number_to = models.IntegerField()

    def __str__(self):
        return self.blank_series
    def save(self, *args, **kwargs):
        # update the branches over here with the number_from & number_to range
        pass

POST_SAVE信号 在这里阅读如何做post_save信号 https://docs.djangoproject.com/en/3.0/ref/signals/#django.db.models.signals.post_save