gpt4 book ai didi

python - 模型内部的 IntegrityError.Django 中的 DoesNotExist 异常

转载 作者:太空宇宙 更新时间:2023-11-04 05:55:17 25 4
gpt4 key购买 nike

我尝试将网页保存到数据库,url 应该是唯一的。如果 url 已经存在,我只需要在网页类和搜索类之间创建关系。但问题是,即使数据库为空并且操作发生在 DoesNotExist 异常中,我也会不断收到此 IntegrityError。请帮我解决我的问题。

这是执行保存的 block views.py 代码。

websearch.startSearch(maxPage=2)
for result in websearch.searchResult:
try:
web = Webpage.objects.get(url=result)
searching.objects.create(webpage=web, keyword=keyword)
except Webpage.DoesNotExist:
web = Webpage.objects.create(url=result)
searching.objects.create(webpage=web, keyword=keyword)

这是网页和搜索模型

class Webpage(models.Model) :
"webpage from search result and client's websites"
domain = models.ForeignKey(Domain, blank=True, null=True)
webhosting = models.ForeignKey(WebHosting, blank=True, null=True)
url = models.URLField(max_length=250, blank=False, unique=True)
html_page = models.TextField(blank=True, null=True)
inspect_status = models.BooleanField(blank=True)
scam_status = models.BooleanField(blank=True)
report_status = models.BooleanField(blank=True)
access_status = models.BooleanField(blank=True)
whitelist_status = models.BooleanField(blank=True)
compare_to = models.ForeignKey('self', blank=True, null=True)
def __unicode__(self):
return self.url

class searching (models.Model):
'information on each searching activity'
keyword = models.ForeignKey(Keyword, blank=True, null=True)
token = models.ForeignKey(Token, blank=True, null=True)
webpages = models.ForeignKey(Webpage)
date = models.DateField(auto_now=True)
class comparison(models.Model):
'''comparing website to other websites with the same event and label'''
source = models.ForeignKey(Webpage, related_name='compare_source')
destination = models.ForeignKey(Webpage, related_name='compare_destination')
time = models.DateTimeField(auto_now=True)
fuzz_ratio = models.FloatField()
fuzz_partial_ratio = models.FloatField()
fuzz_token_sort_ratio = models.FloatField()
fuzz_token_set_ratio = models.FloatField()
difflib_ratio = models.FloatField()
difflib_quick_ratio = models.FloatField()
difflib_real_quick_ratio = models.FloatField()
levenshtein_ratio = models.FloatField()
levenshtein_seqratio = models.FloatField()

最佳答案

你不需要处理异常,你可以使用 get_or_create 内置函数。

websearch.startSearch(maxPage=2)
for result in websearch.searchResult:

webpage, created = Webpage.objects.get_or_create(url=result)
#webpage is a instance
#created is True is a new instance was created or False if it already existed.

还有,你打错了

searching.objects.create(webpage=web, keyword=keyword)

应该是

searching.objects.create(webpages=web, keyword=keyword)

Searching对象有webpages属性,不是网页,需要添加's'

关于python - 模型内部的 IntegrityError.Django 中的 DoesNotExist 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28185537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com