2016-05-23 9 views
0

Ich habe die Diagnosis Tabelle in models.py. Die diagnosis_option kann mehrere Werte (möglicherweise mehrere) aus dem Feld diagnosis_option_value speichern.Django: Erstellen Sie eine ManyToMany() - Beziehung zum Speichern von Multivalen

Hier ist meine Diagnosis Tabelle.

class Diagnosis(models.Model): 

    age_of_diagnosis = models.IntegerField(null=True,blank=True) 
    age_at_onset_of_symptoms = models.IntegerField(null=True,blank=True) 
    diagnosis_option_value = (
     ('', 'Please select a diagnosis'), 
     ('b-thalassaemia syndromes', 'b-thalassaemia syndromes'), 
     ('a-thalassaemia syndromes', 'a-thalassaemia syndromes'), 
     ('Sickle cell syndromes', 'Sickle cell syndromes'), 
     ('Other haemoglobin variants','Other haemoglobin variants'), 
     ('Rare cell membrane disorders','Rare cell membrane disorders'), 
     ('Rare cell enzyme disorders','Rare cell enzyme disorders'), 
     ('Congenital dyserythropoietic anaemias','Congenital dyserythropoietic anaemias') 
    ) 
    diagnosis_option = models.CharField(max_length=30) 
    record_of_genotype = models.CharField(max_length=45,null=True,blank=True) 
    # icd_10_code = models.ForeignKey(icd_10) 
    icd_10_code = models.CharField('ICD-10 code', max_length=20,null=True,blank=True) 
    # icd_10_desc = models.CharField('ICD-10 description',max_length=80,null=True,blank=True) 
    icd_10_desc = models.ForeignKey(icd_10) 
    orpha_code = models.CharField('Oprha code', max_length=20,null=True,blank=True) 
    comment = models.CharField(max_length=100,null=True,blank=True) 
    #diagnosis_genotype = models.CharField('Diagnosis genotype', max_length=100, null=True, blank=True) 

    diagnosis_circumstances = models.CharField(max_length=150) 
    diagnosis_circumstances_date = models.DateField('Date of diagnosis',null=True,blank=True) 
    date_of_input= models.DateField(null=True,blank=True) 
    pub_date = models.DateTimeField(auto_now=True) 
    author = models.ForeignKey(User) 
    patient = models.ForeignKey(Demographic) 
    history = HistoricalRecords() 


    def __str__(self): 
     return str(self.patient) 

Um es mehrere Werte zu speichern vorgeschlagen wurde eine andere Tabelle zu erstellen ManytoMany Beziehung zu haben.

habe ich DiagnosisOption wie unten:

class DiagnosisOption(models.Model): 
    diag_option_value = models.CharField(max_length=30) 
    diag_option = models.ManyToManyField(Diagnosis) 

    def __str__(self): 
     return self.diag_option 

Wie diag_option erhalten Werte von diagnosis_option?

In forms.py ist mein Code der eine unten. Für diagnosis_option verwende ich forms.CheckboxSelectMultiple() Widget.

class DiagnosisForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs): 

     super(DiagnosisForm, self).__init__(*args, **kwargs) 

     self.fields['diagnosis_circumstances_date']= forms.DateField(label=('Date'),required=False, 
     widget=DateTimePicker(options={"format": "YYYY-MM-DD", 
             "pickTime": False, 
             "startDate": "1900-01-01"})) 

     self.helper=FormHelper(form=self) 

     self.fields['icd_10_desc']= forms.ModelChoiceField(queryset=icd_10.objects.all(), 
            widget=autocomplete_light.ChoiceWidget("icd_10Autocomplete")) 
     self.fields['icd_10_desc'].label = "ICD-10 description" 
     diagnosis_option_value = (
     ('b-thalassaemia syndromes', 'b-thalassaemia syndromes',), 
     ('a-thalassaemia syndromes', 'a-thalassaemia syndromes'), 
     ('Sickle cell syndromes', 'Sickle cell syndromes'), 
     ('Other haemoglobin variants','Other haemoglobin variants'), 
     ('Red cell membrane disorders','Red cell membrane disorders'), 
     ('Red cell enzyme disorders','Red cell enzyme disorders'), 
     ('Congenital dyserythropoietic anaemias','Congenital dyserythropoietic anaemias') 
    ) 
     self.fields['diagnosis_option']=forms.MultipleChoiceField(choices=diagnosis_option_value, widget=forms.CheckboxSelectMultiple()) 


     diagnosis_circumstances_value = (
     ('Antenatal diagnosis','Antenatal diagnosis'), 
     ('Neonatal diagnosis','Neonatal diagnosis'), 
     ('By the presence of affected related','By the presence of affected related'), 
     ('Clinical diagnosis', 'Clinical diagnosis'), 
     ('Other','Other') 

     ) 
     self.fields['diagnosis_circumstances']=forms.MultipleChoiceField(choices=diagnosis_circumstances_value, widget=forms.CheckboxSelectMultiple()) 
     #self.fields['patient'].queryset = Demographic.objects.filter(patient_id=self.instance.patient) 
     self.helper.field_class = 'col-md-8' 
     self.helper.label_class = 'col-md-3' 

     #self.helper.form_class = 'forms-horizontal' 
     self.helper.layout = Layout(
      Fieldset (
       # 'patient', 
       '<b>Diagnosis information</b>', 
       Div(
        #HTML(u'<div class="col-md-2"></div>'), 
        Div('age_of_diagnosis',css_class='col-md-6'), 
        Div('age_at_onset_of_symptoms',css_class="col-md-6"), 
        css_class='row', 
        ), 



       'diagnosis_option', 
       'record_of_genotype', 
       'icd_10_desc', 
       'icd_10_code', 
       'orpha_code', 
       'comment', 
       ), 

      Fieldset(
       '<b>Diagnosis circumstances</b>', 
       'diagnosis_circumstances', 
       'diagnosis_circumstances_date', 
       #'diagnosis_circumstances_caring_year', 
       ), 



      FormActions(
       Submit('submit', "Save changes"), 
       Submit('cancel',"Cancel") 
      ), 
     ) 
     self.helper.form_tag = False 
     self.helper.form_show_labels = True 

    class Meta: 
     model = Diagnosis 
     exclude = ['patient', 'author'] 

     list_display = ('patient', 'pub_date', 'author') 
     # autocomplete_js_attribute={'name': 'icd_10_code'} 

DIES IST meine Lösung in Bezug auf AKS vorgeschlagene Lösung:

models.py

class DiagnosisOption(models.Model): 
    diagnosis_option_value = (
     ('', 'Please select a diagnosis'), 
     ('b-thalassaemia syndromes', 'b-thalassaemia syndromes'), 
     ('a-thalassaemia syndromes', 'a-thalassaemia syndromes'), 
     ('Sickle cell syndromes', 'Sickle cell syndromes'), 
     ('Other haemoglobin variants','Other haemoglobin variants'), 
     ('Rare cell membrane disorders','Rare cell membrane disorders'), 
     ('Rare cell enzyme disorders','Rare cell enzyme disorders'), 
     ('Congenital dyserythropoietic anaemias','Congenital dyserythropoietic anaemias') 
    ) 

    diag_option = models.CharField(max_length=50) 

    def __str__(self): 
     return self.diag_option 

class Diagnosis(models.Model): 

    ... 
    diagnosis_option = models.ManyToManyField(DiagnosisOption) 

forms.py: In DiagnosisForm:

diagnosis_option_value = (
     ('b-thalassaemia syndromes', 'b-thalassaemia syndromes',), 
     ('a-thalassaemia syndromes', 'a-thalassaemia syndromes'), 
     ('Sickle cell syndromes', 'Sickle cell syndromes'), 
     ('Other haemoglobin variants','Other haemoglobin variants'), 
     ('Red cell membrane disorders','Red cell membrane disorders'), 
     ('Red cell enzyme disorders','Red cell enzyme disorders'), 
     ('Congenital dyserythropoietic anaemias','Congenital dyserythropoietic anaemias') 
    ) 
     self.fields['diagnosis_option']=forms.MultipleChoiceField(choices=DiagnosisOption.objects.all().values_list('id','diag_option'), widget=forms.CheckboxSelectMultiple()) 

views.py:

In request.method=POST:

my_diagnosis = DiagnosisForm(request.POST, prefix='diag') 

for formfield in my_diagnosis: 
       dia_id = formfield.name 
       if formfield.name == 'diagnosis_option': 
        dig_opt_list = formfield.value() 

my_diagnosis_object = my_diagnosis.save(commit=False) 
      my_diagnosis_object.author = request.user 
      my_diagnosis_object.patient = my_demographics_object 
      my_diagnosis_object.save() 

      for x in xrange(0, len(dig_opt_list)): 
       my_diagnosis_object.diagnosis_option.add(dig_opt_list[x]) 

Antwort

0

ich es in folgenden Weise nähern würde:

Verschieben Sie die Auswahl an DiagnosisOption Klasse:

class DiagnosisOption(models.Model): 
    diagnosis_option_value = (
     ('', 'Please select a diagnosis'), 
     ('b-thalassaemia syndromes', 'b-thalassaemia syndromes'), 
     ('a-thalassaemia syndromes', 'a-thalassaemia syndromes'), 
     ('Sickle cell syndromes', 'Sickle cell syndromes'), 
     ('Other haemoglobin variants','Other haemoglobin variants'), 
     ('Rare cell membrane disorders','Rare cell membrane disorders'), 
     ('Rare cell enzyme disorders','Rare cell enzyme disorders'), 
     ('Congenital dyserythropoietic anaemias','Congenital dyserythropoietic anaemias') 
    ) 

    diag_option = models.CharField(max_length=30) 

    def __str__(self): 
     return self.diag_option 

Und, fügen Sie es als ManyToManyField in Diagnosis Klasse :

class Diagnosis(models.Model): 

    # other fields 

    diagnosis_options = models.ManyToManyField(DiagnosisOption) 
+0

Ich glaube nicht, dass dies ein Viele-zu-Viele sein will. Da Sie die Optionen als Option in DiagnosisOption bereitstellen, benötigen Sie nur einen ForeignKey von dort zurück zur Diagnose. Jede Kombination von (diag_option, Diagnose) ist einzigartig, also keine Notwendigkeit für M2M. –

+0

@DanielRoseman Können Sie mir bitte ein Beispiel geben? – zinon

+0

@DanielRoseman: Das OP möchte mehrere Diagnoseoptionen für eine Diagnose gespeichert haben. – AKS

0

Sie sollten diagnose_option aus der Diagnose entfernen. Dann haben Sie DianosisOption als separates Modell. Wenn Sie eine ManyToMany erstellen, können Sie in beide Richtungen zugreifen. Hier im folgende Beispiel habe ich den Namen diagnosis_options zur Diagosis -> DiagnosisOption Beziehung, so dass Sie werden in der Lage sein, alle Optionen zu erhalten, indem Sie:

yourDiagnosisInstace.diagnosisOptions.all() 

Hoffen, dass es leider hilft, wenn es ein Syntaxfehler, ich hatte keine Zeit, es zu testen.

class DiagnosisOption(models.Model): 
diagnosis_option_value = (
    ('', 'Please select a diagnosis'), 
    ('b-thalassaemia syndromes', 'b-thalassaemia syndromes'), 
    ('a-thalassaemia syndromes', 'a-thalassaemia syndromes'), 
    ('Sickle cell syndromes', 'Sickle cell syndromes'), 
    ('Other haemoglobin variants','Other haemoglobin variants'), 
    ('Rare cell membrane disorders','Rare cell membrane disorders'), 
    ('Rare cell enzyme disorders','Rare cell enzyme disorders'), 
    ('Congenital dyserythropoietic anaemias','Congenital dyserythropoietic anaemias') 
) 
name = models.CharField(max_length=30, choices=diagnosis_option_value) 
diag_option = models.ManyToManyField(Diagnosis, related_name="diagnosis_options") 

def __str__(self): 
    return self.name 
+0

Danke, aber wie kann ich nach 'DiagnosisOption' speichern? In meinem 'forms.py' habe ich' self.fields ['DiagnosisOption__name'] = forms.MultipleChoiceField (choices = diagnose_option_value, widget = forms.CheckboxSelectMultiple()) '. – zinon

+0

Es sollte so etwas wie: 'your_diagnosis.diagnosis_options.add (your_diagnosis_option)' Ich empfehle, die Auswahl (diagnose_option_value) zu entfernen und erstellen und Admin-Ansicht, um Ihre Optionen von dort zu verwalten. Dann in Ihrer Form, um die Auswahl zu treffen, tun Sie einfach etwas wie 'choiches = DiagnosisOption.objects.all()' Lassen Sie es mich wissen! –

Verwandte Themen