Django - how replace values in a model nested in a list of lists

85 views Asked by At

I have two models:

class Document (models.Model):
    dnom = JSONField(blank=True, null=True)
    dphoto = models.ImageField(upload_to='profile_document', blank=False)
    ddate_ajout = models.CharField(max_length=128, unique=False)


class Attacher (models.Model):
    name = models.CharField(max_length=128, unique=True)
    pieces_jointes = JSONField(blank=True, null=True)
    essai = JSONField(blank=True, null=True)

and two associated forms:

class AttacherForm(forms.ModelForm):
    name = forms.CharField(max_length=128, help_text="Please enter the name.")
    pieces_jointes = forms.MultipleChoiceField(choices=[], widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        super(AttacherForm, self).__init__(*args, **kwargs)
        self.fields['pieces_jointes'].choices = [(document.dnom, document.dnom) for document in Document.objects.all()]

    class Meta:
        # Provide an association between the ModelForm and a model
        model = Attacher
        fields = ('name','pieces_jointes')

class DocumentForm(forms.ModelForm):
    dnom = forms.CharField(max_length=128, help_text="Please enter the  name.")
    dphoto = forms.FileField()
    ddate_ajout = forms.CharField(max_length=128, help_text="Please enter the name name.")

        # Provide an association between the ModelForm and a model
        model = Document
        fields = ('dnom','dphoto','ddate_ajout')

The model field pieces_jointes in Attacher is therefore a list of dnom contained in the Document model (added with a MultipleChoiceField field). I would like now to have in essai a list that would match the piece_jointes one but with the values dphoto.

Indeed in my template, I would like to be able to show for each Attacher name each dnom contained in pieces_jointes with the corresponding dphoto value. Can anyone please help ? I am completely lost... Thanks a lot.

1

There are 1 answers

0
Sylvain Biehler On BEST ANSWER
  1. Name your variables in English please. This hurts my eyes (and I'm a native French), but most important it would help anyone who reads the code to understand it.

  2. As pointed in the comments, you may want to modify your model to use ManyToMany relationship. It is aimed for that.

  3. If i understand, you plan to use pieces_jointes and essai to store 2 lists of related dnom and dphoto. Again, this is not a proper usage of databases. You should almost never duplicate data. For the record, you may have fields in a form that are not directly linked to a field in the db.

  4. With you models, to get the list of photos corresponding to a pieces_jointes, try this :

    essai = Document.filter(dnom__in = pieces_jointes).values_list('dphoto')

I hope it helps