当 django 表单中的数量为 0 时,如何隐藏外键表单中的项目条目?

How can I hide item entries in foreign key forms when they have 0 quantity in django forms?

我想隐藏为 0 或没有库存的项目条目,我当前的项目借用流程代码是。 class 项目是我在仓库中存放库存的地方,Activity 是我存放借来的订单的地方。

Models.py

class Item(models.Model):

ItemName = models.CharField(max_length=255, blank=True, null=True)
Quantity = models.IntegerField(null=True, default=1,
    validators=[ 
        MaxValueValidator(100),
        MinValueValidator(0)
    ])
ModelNum = models.CharField(max_length=255, blank=True, null=True)
Category = models.ForeignKey(Category,on_delete=models.CASCADE, null=True)
date_created = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
is_draft = models.BooleanField(default=True)
reorder_level = models.IntegerField(blank=True, default=10,
    validators=[
        MaxValueValidator(100),
        MinValueValidator(1)
    ])

class Meta: 
    verbose_name_plural = 'Item'

def __str__(self):
    return f'{self.ItemName}'



class Activity(models.Model):

Item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True)
staff = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
project_site = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True)
Quantity = models.PositiveIntegerField(null=True, default=1,
    validators=[
        MaxValueValidator(100),
        MinValueValidator(1)
    ])
date_created = models.DateTimeField(auto_now_add=True)
is_draft = models.BooleanField(default=True)
request_status = models.IntegerField(default=0,
    validators=[
        MaxValueValidator(3)
    ])
return_status = models.IntegerField(default=0,
    validators=[
        MaxValueValidator(3)
    ])
note = models.TextField(max_length=255, null=True)


class Meta:
    verbose_name_plural = 'Item Request'

def __str__(self):
    return f'{self.Item}'

Forms.py

class ActivityForm(forms.ModelForm): 

class Meta:
    model = Activity
    fields = ['Item', 'Quantity', 'project_site']

您可以将选择限制为具有 quantity 且至少与 limit_choices_to=… parameter [Django-doc]:

相同的 Item
class Activity(models.Model):
    item = models.ForeignKey(
        Item,
        on_delete=models.CASCADE,
        null=True,
        <strong>limit_choices_to={'Quantity__gt': 0}</strong>
    )
    # …

Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: item instead of Item.