[英]Form to show unique values from Model Django
Learning Django.. I am trying to setup the below and need your expert advise to make it better..学习 Django .. 我正在尝试设置以下内容,需要您的专家建议以使其更好..
I created a model, and form on top of it to show the data.. and I have two questions after the code where I need your advise:)我创建了一个 model,并在其上形成以显示数据.. 在代码之后我有两个问题需要您的建议:)
Model: Model:
class profilestable(models.Model):
choices = [
('Active','Active'),
('Inactive','Inactive')
]
Category = models.CharField(max_length=100)
SubCategory = models.CharField(max_length=100)
product_name = models.CharField(max_length=100)
Status = models.ChoiceField(max_length=20,choices=choices)
def __str__(self):
return self.Category
class Userlist(models.Model):
User = models.CharField(max_length=100)
Categorygroup = models.ForeignKey(profilestable,null=true,on_delete=models.SET_NULL)
def __str__(self):
return self.User
Form:形式:
class userprofileform(forms.ModelForm):
model = Userlist
Fields = ('User','CategoryGroup')
def __init__(self,*args,**kwargs):
super(userprofileform,self).__init__(*args,**kwargs)
Sample data in the profilestable Model:配置文件表 Model 中的示例数据:
Queries:查询:
Request you to please help advise/direct to implement this type of form.请您帮助建议/指导实施此类表格。
Thank you so much.太感谢了。
The structure needs some changes, for example category
should be a parent of sub-category
, and then product
lives below sub-category
, so it would be better to create a separates models for Category
, Sub-category
and Product
in this relation:结构需要进行一些更改,例如
category
应该是sub-category
的父级,然后product
位于sub-category
之下,因此最好在此关系中为Category
、 Sub-category
和Product
创建一个单独的模型:
Category > Sub-category > Product
Since sub-category and products are not unique relation to its parent, use the ForeignKey
Field to connect them. Category > Sub-category > Product
由于子类别和产品与其父类别不是唯一的关系,因此使用ForeignKey
字段将它们连接起来。
Also I see in your sample data
and many products are shinked in 1 row, that is not good in any terms of scaling, performance or order.此外,我在您的
sample data
中看到,许多产品都缩小为 1 行,这在缩放、性能或订单方面都不好。
Yet I cannot see the usecase of your Userlist
model.但是我看不到您的用户列表
Userlist
的用例。
Once done the above please refer this answer to create your drop down menu, althought the distinct at the end is not needed as creating separate model for Category
will avoid the need to duplicate Category
names.完成上述操作后,请参考此答案来创建您的下拉菜单,尽管最后不需要区分,因为为
Category
创建单独的 model 将避免重复Category
名称的需要。 Then on form submition, you Query for the correct Category
and Sub-Category
instance and assign it to the ForeignKey
field of your form.然后在提交表单时,查询正确的
Category
和Sub-Category
实例并将其分配给表单的ForeignKey
字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.