简体   繁体   English

AttributeError: 'QuerySet' 对象没有属性 'url'

[英]AttributeError: 'QuerySet' object has no attribute 'url'

this code has this error and I am absolutely lost how to fix it.此代码有此错误,我完全不知道如何修复它。 the code runs fine until it gets to the last object saved in the database and after that it throws this error.代码运行良好,直到它到达保存在数据库中的最后一个对象,然后抛出此错误。 the code is a tool that checks the html of a website between 2 points in time to check if it has an error, even if the website is running well and giving a 200 response code该代码是一种工具,可以在 2 个时间点之间检查网站的 html,以检查它是否有错误,即使该网站运行良好并给出 200 响应代码

This is the error:这是错误:

in check_html print(monitor.url) AttributeError: 'QuerySet' object has no attribute 'url'

def run_monitors():
    delete_from_db()
    monitors = Monitor.objects.filter(is_active=True)
    monitors._fetch_all()
    asyncio.run(_run_monitors(monitors))
    check_html(monitor=monitors)


def check_html(monitor):
    start_time = time.time()
    print(monitor.url)
    # The URLs to compare
    old_html = monitor.html_compare
    new_url = monitor.url

    # Get the HTML of each URL
    try:
        old_html = old_html
        # html1.raise_for_status()
    except Exception as e:
        print(e)


    try:
        html2 = requests.get(new_url)
        html2.raise_for_status()

    except Exception as e:
        print(e)
        return None

    html2 = html2.text[:10000]

    # Create a SequenceMatcher object to compare the HTML of the two URLs
    matcher = difflib.SequenceMatcher(None, old_html, html2)

    similarity_ratio = matcher.ratio() * 100

    response_time = time.time() - start_time

    monitor.html_compare = html2

    html_failure = False
    counter = monitor.fault_counter
    if similarity_ratio <= 90 and counter == 0:
        print(f"The two HTMLs have {similarity_ratio:}% in common.")
        print("change detected")
        html_failure = False
        counter += 1
    elif similarity_ratio > 90 and counter == 0:
        print(f"The two HTMLs have {similarity_ratio:.2f}% in common.")
        print("no change detected")
        html_failure = False
        counter = 0
    elif similarity_ratio > 90 and counter >= 1:
        print(f"The two HTMLs have {similarity_ratio:.2f}% in common.")
        if counter >= 4:
            print(f"HTML fault detected")
            html_failure = True
        else:
            counter += 1
            print(f"checks if fault persists, current fault counter: {counter}")
    elif similarity_ratio < 90 and counter >= 1:
        print("Fault is presumably resolved")
        html_failure = False
        counter = 0
    monitor.fault_counter = counter

    # Print the similarity ratio between the two URLs
    monitor.save(update_fields=['html_compare', 'fault_counter'])
    return html_failure

def send_notifications():
    for monitor in Monitor.objects.all():
            multiple_failures, last_result = has_multiple_failures(monitor)
            result = check_html(monitor)
            no_notification_timeout = (not monitor.last_notified) or \
                                      monitor.last_notified < timezone.now() - timedelta(hours=1)
            if multiple_failures and no_notification_timeout and monitor.is_active:
                _send_notification(monitor, last_result)
            if result:
                _send_notification(monitor, last_result)


I already tried to put a for loop around the 'check_html' function that iterates over every object in monitor but that just returns that monitors can't be iterated over.我已经尝试在循环遍历监视器中的每个对象的“check_html”函数周围放置一个 for 循环,但它只是返回监视器不能被迭代。 it was a long shot but still didn't work这是一个远景,但仍然没有奏效

You have passed the queryset to the check_html() function.您已将查询集传递给check_html()函数。 Using a filter we get one or more items that are iterable.使用过滤器,我们得到一个或多个可迭代的项目。 You can use the for loop in check_html() function or password only one object to the function.您可以在check_html()函数中使用 for 循环或仅将一个对象密码传递给该函数。

I found the issue.我发现了问题。 I had added the check_html function to run on a certain command.我添加了check_html函数以在特定命令上运行。 Which at the end of the script tried to give the whole queryset to the check_html function itself.脚本末尾试图将整个查询集提供给check_html函数本身。

So I just had to remove the check_html function from run_monitor .所以我只需要从run_monitor中删除check_html函数。

Thank you for your help guys.谢谢你们的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM