简体   繁体   English

Django - 如何根据多个字段编辑数据库中的特定行?

[英]Django - How to edit specific row in database based on multiple fields?

So, I'm fairly new to this and haven't had time to sit down and do proper learning.所以,我对此很陌生,还没有时间坐下来进行适当的学习。

What I'm trying to eventually achieve is modifying a timestamp that is initially NULL to the current time, based on employee # and work area.我最终要实现的是根据员工编号和工作区域将最初为 NULL 的时间戳修改为当前时间。 The idea behind this, is a "check-in/check-out" system.这背后的想法是“签入/签出”系统。

First the user enters # and work area and when they "Enter", an entry is created in the database with the #, work area, time in, and a "time out" that is set to NULL.首先,用户输入 # 和工作区,当他们“输入”时,在数据库中创建一个条目,其中 #、工作区、进入时间和设置为 NULL 的“超时”。 Once they're done, they'd just enter their # again, work area, and "Leave" and this should look for the last entry with NULL in time out, and same # and work area and update the time out to the new timestamp.完成后,他们只需再次输入他们的#,工作区,然后“离开”,这应该会查找 NULL 超时的最后一个条目,以及相同的 # 和工作区,并将超时更新为新的时间戳。 In the case this doesn't exist then it would create a new entry but alert the user.如果这不存在,那么它将创建一个新条目但会提醒用户。

forms.py forms.py

class WarehouseForm(forms.Form):
    class Meta:
        model = EmployeeWorkAreaLog
        fields = ('employee_number', 'work_area', 'station_number')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['station_number'].queryset = StationNumber.objects.none()

        if 'work_area' in self.data:
            try:
                work_area_id = int(self.data.get('work_area'))
                self.fields['station_number'].queryset = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name')
            except (ValueError, TypeError):
                pass
        elif self.instance.pk:
            self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name')

models.py模型.py

class WorkArea(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class StationNumber(models.Model):
    work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
    employee_number = models.IntegerField(max_length=50, help_text="Employee #", blank=False)
    work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area")
    station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True)
    time_in = models.DateTimeField(auto_now_add=True, help_text="Time in", null=True, blank=True)
    time_out = models.DateTimeField(blank=True, help_text="Time out", null=True)

    def __str__(self):
        return self.employee_number

views.py视图.py

class EnterExitArea(CreateView):
    model = EmployeeWorkAreaLog
    template_name = "operations/enter_exit_area.html"
    form_class = WarehouseForm


    def form_valid(self, form):
        if 'enter_area' in self.request.POST:
            form.save()
            return HttpResponseRedirect(self.request.path_info)
        elif 'leave_area' in self.request.POST:
            return HttpResponseRedirect(self.request.path_info)


def load_stations(request):
    work_area_id = request.GET.get('work_area')
    stations = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name')
    return render(request, 'operations/station_number_dropdown_options.html', {'stations': stations})

You can filter your EmployeeWorkAreaLog model like this:您可以像这样过滤您的EmployeeWorkAreaLog model:

employee_log = EmployeeWorkAreaLog.objects.filter(employee_number=1234,work_area__name="East_Bay",station_number=1,time_out__isnull=True).first()
if not employee_log:
    # create new entry and alert user
else:
    employee_log.timeout = current_date_time
    employee_log.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM