2015-12-28 74 views
0

我有兩個表朵蒙特和郵遞區號:Django的IntegrityError NOT NULL約束失敗

class Pincode(models.Model): 
    pincode = models.CharField("PinCode", max_length=6, null=False) 
    geom = GeopositionField("Location") 

class Topmost(models.Model): 
    pincode = models.ForeignKey(Pincode, unique=True) 
    rating_pincode = models.CharField("Total Rating points", max_length=255, null=True, blank=True) 
    frequency = models.CharField("Number of user", max_length=255, null=True, blank=True) 
    normalized_rank = models.FloatField(null=True, blank=True) 

現在我想創建一個自動錄入創建新pincodes時,最頂層。 所以在views.py:

id_past_entries = Topmost.objects.all().values_list('pincode_id', flat=True) 
    new_entries = Pincode.objects.exclude(id__in=id_past_entries).values_list('id', flat=True) 

    for new_id in new_entries: 
     new = Pincode.objects.get(id = new_id) 
     Topmost.objects.create(pincode=new,rating_pincode=0, frequency=0, normalized_rank=0) 
     Topmost().save() 

但它給錯誤

IntegrityError: NOT NULL constraint failed: display_topmost.pincode_id

任何想法?

回答

0

你爲什麼用Topmost().save()

Topmost.objects.create(pincode=new,rating_pincode=0, frequency=0, normalized_rank=0)已經創建你的對象

+0

你試圖刪除此行? –

+0

是的,我試了一下。 –

0

首先,你不應該做的最頂層()。保存()作爲創建功能做同樣的事情。其次,只要確保數據庫中的所有PIN碼都附有一個ID即可。這可能是存在非空約束完整性錯誤的原因。

0

我認爲這是更好地在這種情況下(https://docs.djangoproject.com/en/1.9/topics/signals/ )使用的信號,從view.py刪除代碼,並在models.py添加信號:

from django.dispatch import receiver 

class Pincode(models.Model): 
    pincode = models.CharField("PinCode", max_length=6, null=False) 
    geom = GeopositionField("Location") 

class Topmost(models.Model): 
    pincode = models.ForeignKey(Pincode, unique=True) 
    rating_pincode = models.CharField("Total Rating points", max_length=255, null=True, blank=True) 
    frequency = models.CharField("Number of user", max_length=255, null=True, blank=True) 
    normalized_rank = models.FloatField(null=True, blank=True) 

@receiver(post_save, sender=Pincode) 
def create_topmost(sender, instance=None, created=False, **kwargs): 
    if created: 
     Topmost.objects.create(pincode=instance, rating_pincode="0", frequency="0", normalized_rank=0) 
相關問題