简体   繁体   English

Django:限制模型中的选择。PrimaryKey 的字符域

[英]Django: Limit choices in a models.Charfield by PrimaryKey

Another question from me tonight and I hope I can explain it adequately:今晚我的另一个问题,我希望我能充分解释:

I got three classes in my "models.py":我的“models.py”中有三个类:

class Customer(models.Model):
    full_name = models.CharField(max_length=100, null=True, unique=True)
    short_name = models.CharField(max_length=8, null=True, unique=True)

class Project(models.Model):
    customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE)
    name = models.CharField(max_length=255, null=True, unique=True)
    ...

class Entry(models.Model):
    user = models.ForeignKey(User, null=True, blank=False, on_delete=models.CASCADE)
    customer = models.ForeignKey(Customer, null=True, blank=False, on_delete=models.CASCADE)
    project = models.ForeignKey(Project, null=True, blank=False, on_delete=models.CASCADE)
    date = models.DateField()
    shortText = models.CharField(max_length=100, null=False, blank=False)
    ...

Note: One Customer can have multiple Projects.注意:一位客户可以拥有多个项目。

On one of my sites there's a table with buttons beside each "Customer".在我的一个网站上,每个“客户”旁边都有一个带有按钮的表格。 The plan is, that it should lead me to another page, were the user can write and save his "Entry".计划是,它应该引导我到另一个页面,如果用户可以编写并保存他的“条目”。 Right now, the PrimaryKey inside the Button/Link contains the ID of the "Customer".现在,按钮/链接中的 PrimaryKey 包含“客户”的 ID。

My question is: is it possible to limit the choices of the "Project" (inside a Drop-Down-Menu) to the "Customer" that has been clicked on?我的问题是:是否可以将“项目”(在下拉菜单中)的选择限制为已单击的“客户”? And is creating a ModelForm the right thing to do?并且创建一个 ModelForm 是正确的做法吗?

Thanks to all of you and a good night!谢谢大家,晚安!

Well, don't know if this is the right way, but I found a solution for my problem:好吧,不知道这是否是正确的方法,但我找到了解决我的问题的方法:

  1. Wrote a "forms.ModelForm" for my view-function...为我的视图功能写了一个“forms.ModelForm”......

     class EntryForm(ModelForm): class Meta: model = Entry fields = '__all__' def __init__(self, *args, pk, **kwargs): super().__init__(*args, **kwargs) self.fields['project'].queryset = Project.objects.filter(customer_id=pk)
  2. Insert my ModelForm into the view-function...将我的 ModelForm 插入视图功能...

     def WriteEntry(request, pk): form = EntryForm(pk=pk) if request.method =='POST': form = EntryForm(request.POST, pk) if form.is_valid(): form.save()... context = {'form': form} return render(request, '...html', context)

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

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