Django

时间:2018-11-30 10:46:01

标签: django django-models

每次输入新值“ sku”(不是创建新条目)时,我都需要更新我的表,但是只有在选择的“客户端”相同的情况下,它才必须发生。如果“客户端”不同,则模型应添加一个具有相同“ sku”但具有不同“客户端”的新对象。

我已尝试在我的models.py中执行以下操作:

class ProductList(models.Model):
    id_new = models.IntegerField(primary_key=True)
    sku = models.CharField(primary_key=False, max_length=200)
    client = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    name = models.CharField(max_length=256)
    description = models.CharField(max_length=1000)
    storage = models.CharField(max_length=256)
    cost_price = models.CharField(max_length=256)
    sell_price = models.CharField(max_length=256)
    ncm = models.CharField(max_length=256)
    inventory = models.IntegerField(null=True)

    class Meta:
        unique_together = (('sku', 'client'),)

但是它不起作用。我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以尝试这样:

# form

class MyForm(forms.ModelForm):
    class Meta:
        model = ProductList

    def save(self, *args, **kwargs:
        client = self.cleaned_data.get('client')  # get client from form cleaned_data
        if hasattr(self.instance, 'pk') and self.instance.client != client:  # check if client match's already existing instance's client
            self.instance.pk = None  # make a duplicate instance
            self.instance.client = client  # change the client

        return super(MyForm, self).save(*args, **kwargs)

# views.py
# ...    
def my_view(request, id): 
    instance = get_object_or_404(ProductList, id=id)
    form = MyForm(request.POST or None, instance=instance)
    if form.is_valid():
        form.save()
        return redirect('next_view')
    return render(request, 'my_template.html', {'form': form}) 

更新

嗯,您也可以覆盖模型。您可以尝试这样:

  # Untested Code but should work
  def save(self, *args, **kwargs):
     if self.pk:
        current_instance = self.__class__.objects.get(pk=self.pk)
        if current_instance.client != self.client:
           self.pk = None
     return super(ProductList, self).save(*args, **kwargs)