我有两张桌子Topmost和Pincode:
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约束失败:display_topmost.pincode_id
任何想法??
答案 0 :(得分:0)
为什么使用Topmost().save()
?
Topmost.objects.create(pincode=new,rating_pincode=0, frequency=0, normalized_rank=0 )
已经创建了您的对象
答案 1 :(得分:0)
首先,你不应该做TopMost()。save(),因为create函数做同样的事情。其次,只需确保数据库中的所有PinCode都附加了一个id。这可能是存在非空约束的完整性错误的原因。
答案 2 :(得分: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 )