Python Django多对多字段,带有可用的应用程序标签
嗨,一个模特有可能拥有一个包含所有可用应用程序的ManyToManyField作为其选择吗 假设我在我的settings.py中安装了这些应用程序 然后在我的模型中,我有这个模型Python Django多对多字段,带有可用的应用程序标签,python,django,Python,Django,嗨,一个模特有可能拥有一个包含所有可用应用程序的ManyToManyField作为其选择吗 假设我在我的settings.py中安装了这些应用程序 然后在我的模型中,我有这个模型 class IPAddreses(models.Model): ip = models.GenericIPAddressField() apps = models.ManyToManyField(ContentType, blank=True) # The apps field should b
class IPAddreses(models.Model):
ip = models.GenericIPAddressField()
apps = models.ManyToManyField(ContentType, blank=True)
# The apps field should be the choices of the avialable apps on the settings.py
可能吗?可能不可能,但您可以做的只是创建一个新的模型/表,该模型/表使用已安装的应用程序列表进行更新,并向该模型添加多对多关系。 这将是一个更简单、更灵活的解决方案。
因为您可能会跟踪(如果需要)与从已安装应用列表中删除的应用之间的关系。可能不可能,但您可以做的只是使用已安装应用列表更新一个新模型/表,并向该模型添加多对多关系。 这将是一个更简单、更灵活的解决方案。 因为您可能会跟踪(如果需要)与从已安装应用列表中删除的应用的关系。可能的解决方案:
# models.py
class IPAddressApp(models.Model):
ip = models.GenericIPAddressField()
app = models.CharField(max_length=100)
class Meta:
unique_together = (
("ip", "app"),
)
# forms.py
from django.apps import apps
class IPAddressAppForm(forms.ModelForm):
app = forms.ChoiceField()
class Meta:
model = models.IPAddressApp
fields = (
'ip',
'app',
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['app'].choices = self.get_apps()
def get_apps(self):
return [(app, "{} ({})".format(config.verbose_name, app)) for
app, config in apps.app_configs.items()]
其他选择:
- 对于多对多字段,使用
模型,并使用应用程序方法上的上述代码填充它应用程序
- 对应用程序使用
()ArrayField(CharField)
- 可能的解决方案:
# models.py
class IPAddressApp(models.Model):
ip = models.GenericIPAddressField()
app = models.CharField(max_length=100)
class Meta:
unique_together = (
("ip", "app"),
)
# forms.py
from django.apps import apps
class IPAddressAppForm(forms.ModelForm):
app = forms.ChoiceField()
class Meta:
model = models.IPAddressApp
fields = (
'ip',
'app',
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['app'].choices = self.get_apps()
def get_apps(self):
return [(app, "{} ({})".format(config.verbose_name, app)) for
app, config in apps.app_configs.items()]
其他选择:
- 对于多对多字段,使用
模型,并使用应用程序方法上的上述代码填充它应用程序
- 对应用程序使用
()ArrayField(CharField)