IntegrityError:yonetim ders.ogretim elemani id可能不是NULL

时间:2014-12-30 22:53:16

标签: django

我的models.py:

from django.db import models


class OgretimElemani(models.Model):
    adi = models.CharField(max_length=50)
    soyadi = models.CharField(max_length=50)
    telefonu = models.CharField(max_length = 10 , blank=True)
    e_posta_adresi = models.EmailField(blank=True)

    def __unicode__(self):
        return '%s %s' % (self.soyadi,self.adi)


class Ders(models.Model):
    kodu = models.CharField(max_length=10)
    adi = models.CharField(max_length=50)
    ogretim_elamani = models.ForeignKey(OgretimElemani)
    tanimi = models.CharField(max_length=1000,blank = True)

    def __unicode__(self): 
        return '%s %s %s' % (self.kodu,self.adi,self.ogretim_elamani)



class Ogrenci(models.Model):
    numarasi = models.IntegerField()
    adi = models.CharField(max_length=50)
    soyadi = models.CharField(max_length=50)
    aldigi_dersler = models.ManyToManyField(Ders)

    def __unicode__(self):  
        return '%s %s %s' % (self.soyadi,self.adi,self.aldigi_dersler)

Django shell:

>>>ders1=Ders(kodu='KIM101', adi='Kimya-1')
>>>ders1.ogretim_elemani=OgretimElemani[0]
>>>ders1.save()

IntegrityError : yonetim_ders.ogretim_elemani_id may not be NULL

1 个答案:

答案 0 :(得分:0)

您必须分配一个已保存到数据库的OgretimElemani实例。

例如,以下内容应该有效。

>>> ders1 = Ders(kodu='KIM101', adi='Kimya-1'
>>> ogretim_elemani = OgretimElemani.objects.all()[0] # fetch the first one from the database
>>> ders1.ogretim_elemani = ogretim_elemani
>>>ders1.save()     

您的示例不是很明确,因为您使用的是OgretimElemani[0]。你不应该重用变量名OgretimElemani,这会使代码混乱。