ManytoManyField Django关系错误

时间:2014-10-09 09:06:07

标签: django object model many-to-many add

当我试图查看我加入患者的过敏症时,我不明白为什么会出现错误?

def create_allergie(request):
    if request.method == 'POST':
        try:
            print 'In create_allergie()'
            allergy = Allergie()
            allergy.name = request.POST['name_allergie']
            allergy.id_allergie = 1065
            allergy.intensity = 10
            allergy.add_by = int(request.POST['user_pk'])
            allergy.deleted = False
            allergy.deleted_date = '20-09-2014:20:10:05'
            allergy.deleted_by = 5
            allergy.save()
            print '-- ALLERGIE SAVE --'
            pk_patient = int(request.POST['patient_pk'])
            my_patient = get_object_or_404(Patient, pk=pk_patient)
            print my_patient
            allergy.patient.add(my_patient)
            print '---- DISPLAY TABLE ----'
            print 'PATIENT : ', allergy.patient.all()
            print 'ALLERGY : ', my_patient.allergie_set.all()
        except Exception, b:
            print b
            raise b
        return render_json([])

我把输出结果放在这里:

在create_allergie()

- ALLERGIE SAVE -

移动Joee

---- DISPLAY TABLE ----

患者:[患者:流动的Joee]

过敏:' Allergie'对象没有属性' content'

我也给你模特' Allergie' :

class Allergie(models.Model):
    name = models.CharField(max_length=25, verbose_name="Nom de l'allergie")
    id_allergie = models.IntegerField()
    intensity = models.IntegerField()
    add_date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date d'ajout de l'allergie")
    add_by = models.IntegerField()
    deleted = models.BooleanField()
    deleted_date = models.CharField(max_length=255, verbose_name="Date de suppression de l'allergie")
    deleted_by = models.IntegerField()
    patient = models.ManyToManyField(Patient)

def __unicode__(self):
    return unicode(self.content)

class Meta:
    verbose_name = "Allergie"
    verbose_name_plural = "Allergies"

我希望有人可以帮助我......谢谢

1 个答案:

答案 0 :(得分:1)

错误发生在def __unicode__。你得到的错误是' Allergie'对象没有属性' content'。打印过敏时,Django会尝试打印def __unicode__中定义的内容。此方法生成错误。您可以将其更改为:

def __unicode__(self):
    return self.name