你如何保持ManyToMany关系的最新状态?

时间:2018-04-25 17:05:02

标签: django

我有以下课程:

class Plugin(models.Model):
    pass 

class Instance(models.Model):
    plugins = models.ManyToManyField(Plugin, blank=True, null=True)

我的目标是编写一个cron作业,该作业从此实例获取插件列表以反映instance_plugin关系。 这意味着如果在现实生活中从实例中删除插件,则必须在此处反映

for instance in Instance.objects.all():
    url = 'http://{}/wordpress_plugins'.format(instance.ip_address)
    ... 
    plugins = []
    for path, dic in response.json().items():
        plugin, created = Plugin.objects.update_or_create(
             ... 
        )
        plugins.add(plugin)

    instance.plugin_set = plugins

我正在TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use plugins.set() instead.

我正在做的最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

也许这可以做你想做的事 如果您使用所有模型所具有的字段编辑代码, 我可以为你提供一个更好的。

for instance in Instance.objects.all():
    url = 'http://{}/wordpress_plugins'.format(instance.ip_address)
    ... 
    plugins = []
    for path, dic in response.json().items():
        plugin, created = Plugin.objects.update_or_create(
            ... 
        )
        plugins.add(plugin)

    # First Option
    # We add each plugin from the Plugins List
    [instance.plugins.add(item) for item in plugins]
    # We loop through the instance to see which plugin is not in the New List Plugin, we delete it
    for plug in instance.plugins.all():
        if plug not in plugins:
            plug.delete()


    # 2nd Option
    # We clear the intance ManyToMany Field
    instance.plugins.clear()
    # We add each plugin from the Plugins List
    [instance.plugins.add(item) for item in plugins]
    # We loop The all The Plugin, to see which plugin does not have a reverse relation to instance
    for plug in Plugin.objects.all():
        if not plug.instance_set.all():
            plug.delete()