小编Cos*_*tin的帖子

Django .get()返回一个元组,而不是对象

我有一个简单的函数,看起来像这样:

parent_key = SeoKeys.objects.get(view_id=view_id, key_nbr=key_nbr)
    if parent_key.status != 'active':
        parent_key.status = status
        parent_key.save()

    metrics, created = SeoMetrics.objects.get_or_create(
                                                        seo_url = url_sent,
                                                        date = date,
                                                        parent_key = parent_key,
                                                        defaults = {
                                                                'parent_key':parent_key,
                                                                'seo_url': url_sent,
                                                                'url_found':url_found,
                                                                'position':position,
                                                                }
                                                        )
Run Code Online (Sandbox Code Playgroud)

现在理论上这应该工作,但是我得到以下错误:

ValueError: Cannot assign "(<SeoKeys: SeoKeys object>,)": "SeoMetrics.parent_key" must be a "SeoKeys" instance.
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为它是一个元组.如果我这样做'parent_key':parent_key[0]会保存它.然而,这似乎是一个相当黑的解决方案,我想更明白为什么会发生这种情况.有任何想法吗?

我的模型看起来像这样:

class SeoMetrics(models.Model):
    parent_key = models.ForeignKey('SeoKeys', on_delete=models.CASCADE)
Run Code Online (Sandbox Code Playgroud)

编辑: 添加完整错误:

Internal Server Error: /hook/
Traceback (most recent call last):
  File "/Users/Costantin/GDrive/Analytic.me/dev/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File …
Run Code Online (Sandbox Code Playgroud)

django postgresql python-3.x

2
推荐指数
1
解决办法
493
查看次数

同时发出多个异步请求

我正在尝试同时调用~300个API调用,这样我最多可以在几秒内得到结果.

我的伪代码看起来像这样:

def function_1():
    colors = ['yellow', 'green', 'blue', + ~300 other ones]
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    res = loop.run_until_complete(get_color_info(colors))

async def get_color_info(colors):
    loop = asyncio.get_event_loop()
    responses = []
    for color in colors:
        print("getting color")
        url = "https://api.com/{}/".format(color)
        data = loop.run_in_executor(None, requests.get, url)
        r = await data
        responses.append(r.json())
    return responses
Run Code Online (Sandbox Code Playgroud)

这样做我getting color每隔一秒左右打印一次,代码需要永远,所以我很确定它们不会同时运行.我究竟做错了什么?

python python-3.x python-requests python-asyncio

2
推荐指数
1
解决办法
2819
查看次数

类型对象'X'没有带有django的属性'DoesNotExist'

我一直在收到has no attribute DoesNotExist错误.

有什么想法吗?

到目前为止我试过:

    try:
        current_report = Report.objects.get(account_profile=current_profile)
    except Report.DoesNotExist:
        print("report doesn't exist")
        current_report=None
Run Code Online (Sandbox Code Playgroud)

我的调试显示type object 'Report' has no attribute 'DoesNotExist' 在current_report(etc)行:

我也尝试过:

from django.core.exceptions import ObjectDoesNotExist
...
except Report.ObjectDoesNotExist: 
Run Code Online (Sandbox Code Playgroud)

try:
    Report.objects.get(account_profile=current_profile)
except Report.DoesNotExist:
    print("report doesn't exist")
    current_report=None
Run Code Online (Sandbox Code Playgroud)

try:
    Report.objects.get(account_profile=current_profile)
except ObjectDoesNotExist:
    print("report doesn't exist")
    current_report=None
Run Code Online (Sandbox Code Playgroud)

为什么类型对象'X'没有属性'DoesNotExist'?我正在使用django.

在我的Models.py中,我有:

class Report(models.Model):
    account_profile = models.ForeignKey(Profile)
    total_visitors = models.CharField(max_length=200, blank=True, null=True)
    last_week_visitors = models.CharField(max_length=200, blank=True, null=True)
    new_visitors_this_wk = models.CharField(max_length=200, blank=True, null=True)
    new_visitors_last_wk = models.CharField(max_length=200, blank=True, null=True) …
Run Code Online (Sandbox Code Playgroud)

python django

1
推荐指数
2
解决办法
3115
查看次数

为多个模型重用 Django_filter

我有一个非常基本的过滤器设置(使用django-filter),它允许我使用日期范围从我的 django rest api 查询我的数据:

/api/v2/metrics/?date=2017-01-01
/api/v2/metrics/?start=2017-03-03&end=2017-04-01
/api/v2/metrics/?start=2017-03-03
etc.
Run Code Online (Sandbox Code Playgroud)

我的过滤器看起来像这样:

class DateFilter(filters.FilterSet):
start = filters.DateFilter(name='date', lookup_expr='gte')
end = filters.DateFilter(name='date', lookup_expr='lte')
    class Meta:
        model = GaData
        fields = ['date']
Run Code Online (Sandbox Code Playgroud)

我的 API 视图集是:

class GaDataViewSet(viewsets.ModelViewSet):
    queryset = GaData.objects.all()
    serializer_class = GaDataSerializer
    filter_class = DateFilter

    def get_queryset(self): # This returns metrics only for the logged in user
        user_id = self.request.user.id
        return GaData.objects.filter(owner=user_id)

class CountriesViewSet(viewsets.ModelViewSet):
    queryset = GaCountries.objects.all()
    serializer_class = GaCountriesSerializer

    def get_queryset(self): # This returns metrics only for the logged in …
Run Code Online (Sandbox Code Playgroud)

django django-filter django-rest-framework

0
推荐指数
1
解决办法
793
查看次数

仅在 v-for 循环上应用 :style 一次 - vue.js

我正在尝试使用 Vue.js 构建热图表。

我一直在关注为 jquery 制作的这个很棒的教程。

我想避免使用 jquery,并且一切正常,但是我在最后一步遇到了麻烦 $(this).css({backgroundColor:clr});

如何:style为每个单元格只更改一次?现在,一旦它处于循环的最后一个循环,它显然会更改每个单元格的值v-for

我想创建一个watcher每次更改颜色数据属性时都会看到并运行一个单独的函数,例如changeColour: function(color) {// change css}但我不知道将它应用于哪个单元格。

到目前为止,我有:

一个基本的 html 表:

<tbody v-for="page in json">
  <tr>
    <td style = 'background-color: #e5e5ff'> 
    {{page.page_path}} </td>
    <td :style="{ 'background-color': sessionColor }">
    {{page.sessions}} </td>
    <td :style="{ 'background-color': exitColor }">
    {{page.exit_rate}} </td>
    <td :style="{ 'background-color': bounceClr }">
    {{page.bounce_rate}} </td>
    <td :style="{ 'background-color': timeClr }">
    {{page.avg_time_on_page}} </td>
  </tr>
Run Code Online (Sandbox Code Playgroud)

一个具有 4 个颜色属性的 Vue 实例,以及一个负责生成 RGB 值的方法。

在这里,我有完整的jsfiddle,唯一缺少的是V-结合 风格的 …

vue.js vue-component vuejs2

0
推荐指数
1
解决办法
1965
查看次数