0

嗨,我正在编写一个硬件库存应用程序,我想在每次输入新零件时记录,以及任何未来的状态更改/更新。

楷模

class Part(models.Model):
    type = models.ForeignKey(PartType, blank=False)
    bar_code = models.CharField(max_length=50, blank=False, unique=True)
    serial_number = models.CharField(max_length=50, blank=False)
    status = models.ForeignKey(Status, blank=False)

class PartLog(models.Model):
    part = models.ForeignKey(Part, blank=False)
    time_stamp = models.DateTimeField(blank=False, auto_now_add=True)
    old_status = models.ForeignKey(Status, related_name='old_status_related', blank=False)
    new_status = models.ForeignKey(Status, related_name='new_status_related', blank=False)

class Status(models.Model):
    current_status = (
     ("EN", "Entered Database"),
     ("CO", "Checked out"),
     ("CI", "Checked in"),
     ("RM", "Returned for RMA"),
     ("IU", "Currently in use"),     
                    )
    status = models.CharField(max_length=2, choices=current_status)

    def __unicode__(self):
        return unicode(self.status)

信号

@receiver(post_save, sender=Part)
def add_to_partLog(sender, instance, signal, created, *args, **kwargs):

    if created:
        print "Since a new entry has been created, setting old and new status for partlog entry!"
        # Automatically changing status from Entered state to Checked In state
        # Part Table
        instance.status=Status(3)
        instance.save()

        # Setting Old and New status for the first (new) partLog entry for the new added part
        # Part Log table
        oldStatus = Status(1)
        newStatus = Status(3)
        partobj = Part.objects.get(id=instance.pk)
        PartLog.objects.create(part=partobj,old_status=oldStatus, new_status=newStatus)
    else:
        print "Entry already exists!"
        # Retreiving the old status of the Part() record

        oldStatus = ???
        newStatus = instance.status
        partobj = Part.objects.get(id=instance.pk)
        PartLog.objects.create(part=partobj,old_status=oldStatus,new_status=newStatus)

意见

def check_in_part(request):
    err_list=[]
    c = {}
    c.update(csrf(request))

    if request.method == 'POST':
        form = PartForm(request.POST)
        print "form object is created."
        if form.is_valid():  
            form.save()  
            return http.HttpResponseRedirect('/current_count/')    
    else:        
        form = PartForm(initial={'status':1L})
    return render(request,'add_part.html',{
                                           'title':'Add Item',
                                           'form':form
                                           })


# Checking out a part    
def check_out_part(request):
   errlst = []
   c = {}
   c.update(csrf(request))
   # ADD check against DB with the appropriate status "CO" or 3
   if request.method == 'POST':
       form = ModifyPartForm(request.POST)
       if form.is_valid():
           bar_code_form = form.cleaned_data['bar_code']
           try:
               bar_code_model= Part.objects.get(bar_code=bar_code_form)
           except Part.DoesNotExist:
               #FIXME: need to get errlst to user
               errlst.append("Part with bar_code %s does not exist." % bar_code_form)
           else:
                #bar_code_model.check_out()
               bar_code_model.status_id=2L
               bar_code_model.save()
               return http.HttpResponseRedirect('/current_count/')
   else:
       form = ModifyPartForm()
       # Adding default status to Check Out or "CO"
   return render(request, 'remove_part.html',{
                                           'title':'Remove Item',
                                           'form': form,
                                           'errors': errlst,
                                           })

问题在于信号中的 else 子句。if 的第一部分工作得很好。*我不确定如何在保存之前访问“状态”并在保存后使用它。*现在在一个视图中,当我签入一个新零件时,我将初始状态设为“EN”,然后将其自动更改为“CI”。现在对于 check_out 视图,我只想使用条形码搜索 Part(),并适当地更新和记录两个表。最终,我希望能够在下拉列表中列出的其他状态之间进行选择菜单,但那是以后的=)

4

2 回答 2

2

我最终在这里缓存了状态对象是我的答案。

#Signals.py
@receiver(post_save, sender=Part)
def log_entry(sender, instance, created, raw, *args, **kwargs):
    # Using the statuses from the above method to create a PartLog entry. 
    newStatus = instance.status

    if not created:
        # Get old status from current state
        oldStatus = instance._state.old_status
        PartLog.objects.create(part=instance,
                               old_status=oldStatus,
                               new_status=instance.status)
        instance._state.old_status = newStatus
    else:
        PartLog.objects.create(part=instance, old_status=Status(1), new_status=Status(3))

#Models.py

class Part(models.Model):
    type = models.ForeignKey(PartType, blank=False)
    bar_code = models.CharField(max_length=50, blank=False, unique=True)
    serial_number = models.CharField(max_length=50, blank=False)
    status = models.ForeignKey(Status, blank=False)

    def __init__(self, *args, **kwargs):
        super(Part, self).__init__(*args, **kwargs)
        # Caching the existing Part object's status
        if self.pk:
            self._state.old_status = self.status

    def __unicode__(self):
        return unicode(self.bar_code)
于 2012-08-06T17:50:36.910 回答
0

您无法在信号阶段知道该字段的先前值,post_save因为该模型不跟踪字段的 pre-post 值。你有两个选择:

  1. 缓存__init__()模型中的状态字段以及可能的新值save()并检查您的post_save
  2. 对信号中的当前值进行数据库查找pre_save并将其缓存在对象上,以便在保存完成后可以引用它。

我倾向于使用第一种方法并避免数据库查询。您必须知道,提前缓存该字段意味着您不能再在查询中延迟该字段,因为您在__init__

它可能看起来像这样:

class Part(models.Model):
    ...
    def __init__(self, *args, **kwargs):
        super(Part, self).__init__(*args, **kwargs)
        self._status_old_cached = self.status 


@receiver(post_save, sender=Part)
def add_to_partLog(sender, instance, created, *args, **kwargs):
    ...
    else:
        oldStatus = instance._status_old_cached

因为这将立即强制查找该字段,所以请确保您select_related提前在查询中使用此字段:

Part.objects.select_related('status').all()

如果您实际上并不需要状态对象,而只需要id,那么它可能会为您节省查找,因为模型实际上保存了 id:

self._status_id_old_cached = self.status_id
于 2012-07-31T22:02:29.370 回答