Django多对多字段,带有可用的应用程序标签

2024-09-30 08:38:08 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,一个模型有可能有一个包含所有可用应用程序的多域作为它的选择吗

假设我在我的settings.py中安装了这些应用程序

在我的模型里,我有这个模型

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

有可能吗


Tags: appsthepy模型ip应用程序modelsettings
2条回答

可能不可能,但您可以做的只是使用已安装应用程序的列表更新一个新模型/表,并向该模型添加多对多关系。 这将是一个更简单、更灵活的解决方案。 因为您可以跟踪(如果需要)与从已安装应用列表中删除的应用的关系

可能的解决方案:

# 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()]

其他选项:

  • 对于多对多字段,使用App模型并使用应用程序的^{}方法上的上述代码填充它
  • 对应用程序使用ArrayField(CharField)Postgresql only

相关问题 更多 >

    热门问题