小编And*_*ran的帖子

检查属性是否存在的最佳方法是哪种?

哪种方法可以检查属性是否存在?

Jarret Hardie提供了这个答案:

if hasattr(a, 'property'):
    a.property
Run Code Online (Sandbox Code Playgroud)

我看到它也可以这样做:

if 'property' in a.__dict__:
    a.property
Run Code Online (Sandbox Code Playgroud)

一种方法通常比其他方法更常用吗?

python attributes

64
推荐指数
3
解决办法
6万
查看次数

Django源代码中的Model.py在哪里?

我一直在写我的第几个Django模型,想看看的基类,所有的模型扩展(例如:"阶级投票(models.Model"),但找不到模型库类我检查了GitHub上源当我浏览到django.db.models目录我很惊讶地找不到,我可以看一个"Model.py"文件生成此文件?抑或类模型住到别处去?或者是有一些蟒蛇包装魔法还在继续我不熟悉?

python django django-models

7
推荐指数
1
解决办法
1012
查看次数

如何过滤相关对象中的字段?

如果我尝试过滤相关对象中的字段,则Tastypie会返回错误.例如,跑步

curl -H "Accept: application/json" \
     "http://localhost:8080/wordgame/api/v1/rounds/?format=json&players__username=moe"
Run Code Online (Sandbox Code Playgroud)

返回"在'玩家'字段中,查询不允许超过一个级别." 从本质上讲,我正在努力做我目前在Django shell中所做的事情:

Round.objects.all().filter(players__username=moe.username)
Run Code Online (Sandbox Code Playgroud)

我使用以下代码,为简洁起见,我简化了以下代码:

# wordgame/api.py which has tastypie resources
class RoundResource(ModelResource):
    players = fields.ManyToManyField(UserResource, 'players',full=True)
    . . .

    class Meta:
        queryset = Round.objects.all()
        resource_name = 'rounds'
        filtering = {
            'players': ALL,
        }

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'players'
        filtering = {
            'username': ALL,
        }

# wordgame/models.py which has Django models
class Round(models.Model):
    players = models.ManyToManyField(User)
    word = models.CharField(max_length=75)
    . . . 
Run Code Online (Sandbox Code Playgroud)

我假设因为UserResource在字段'username'上定义了一个过滤器,它应该可以工作,但事实并非如此.我甚至尝试将"players__username"添加到RoundResource中的过滤器,但是这也不起作用.

在文档中阅读了有关基本过滤的内容,并查看了GitHub上的代码,但似乎没有任何内容.我还看了一下 …

python django django-models tastypie

5
推荐指数
1
解决办法
3408
查看次数

如何为tastypie设置授权标头?

在请求中传递值作为参数时,它可以工作:

curl "http://localhost:8080/wordgame/api/v1/rounds/?username=test_user&api_key=12345678907a9cb56b7290223165e0a7c23623df&format=json"
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将值作为标头传递时,它不起作用.这导致401:

curl -H "Authorization: ApiKey test_user:12345678907a9cb56b7290223165e0a7c23623df" -H "Accept: application/json" http://localhost:8080/wordgame/api/v1/rounds/
Run Code Online (Sandbox Code Playgroud)

我正在使用Tastypie ApiKeyAuthentication

python django curl tastypie

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

标签 统计

python ×4

django ×3

django-models ×2

tastypie ×2

attributes ×1

curl ×1