简体   繁体   中英

How save a list generate from database to a django model field?

Ok I have a nail in brain with this, I have two model, the first one is autogenerate from the installed apps in settings.py, but I need this installed apps appears in Institution model, because each Institution will have different apps, I can't use ManyToMany field option. Here are my models.py:

class Module(models.Model):
    name = models.CharField(max_length=25)
    enabled = models.BooleanField(default=False)

class Institution(models.Model):
    name = models.CharField(max_length=25)
    module = models.TexField(null=True, blank=True)

Autogenerate list from installed apps in institution/views.py

from settings import INSTALLED_APPS as tuple_apps         

def search_update_modulo():
    list_of_apps = [x for x in tuple_apps if "apps" in x]
    institution_module = []
    for i in list_of_apps:
        i = i[5:]
        if i != "persons":
            institution_module.append(i)
    modules_in_db = Module.objects.all().count()
    if modulos_en_bd < len(modulos_instituciones):
        m = modulo.objects.all().delete()
        for x in modulos_instituciones:
            m = modulo(nombre=str(x).title())
            m.save()

In the template of Institution I send the list of installed apps this way:

{% for m in module_list %}
  <tr class="cursor">
    <td >{{ m }}</td>
    <td > <input id="id_habilitado" name="habilitado" type=checkbox {% if m.habilitado %} checked {% endif %}   value=""> </td>
  </tr>
{% endfor %}

Now my question is, how can I retrieve the values from the template, covert then in a list and save that in module field in the Institution model or any other way solve this. I will appreciate any answer. Thaks

If you are just saving the Module objects when you autogenerate the list then you could have post.save signal in the model class Module(models.Model) which detects if the module is enabled and then you can save that field into Institution field.

Something like this:

class Module(models.Model):
    name = models.CharField(max_length=25)
    enabled = models.BooleanField(default=False)

def update_institution(sender, instance, **kwargs):
     if instance.enabled:
         # Some code here to append the module 
         # to an institution 
         # Institution.module.list(append(instance)

# register the signal
post_save.connect(update_institution, sender=Module, dispatch_uid="update_institution_modules")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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