小编Amy*_*yth的帖子

按第二项(整数值)对元组列表进行排序

我有一个类似于下面的元组列表:

[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
Run Code Online (Sandbox Code Playgroud)

我想按元组内的整数值按升序对此列表进行排序.可能吗?

python tuples list

370
推荐指数
8
解决办法
34万
查看次数

Python:从列表中获取前10个结果

有没有办法可以从列表中获取前10个结果.这样的事情可能是:

list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

list.fetch(10)
Run Code Online (Sandbox Code Playgroud)

python

122
推荐指数
4
解决办法
23万
查看次数

如何在AngularJS部分中保留新行?

在AngularJS部分中,我循环遍历条目列表,如下所示:

<ul class="entries">
    <li ng-repeat="entry in entries">
        <strong>{{ entry.title }}</strong>
        <p>{{ entry.content }}</p>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

{{entry.content}}有些线条的内容被AngularJS忽略了.如何使其保留换行符?

angularjs

59
推荐指数
4
解决办法
5万
查看次数

我该如何扩展服务

我相当新,angularjs并且无法找到任何文档或示例.我要做的是扩展基本服务,以便我可以使用其他服务的基本服务定义的方法.例如,假设我有如下基本服务.

angular.module('myServices', []).

    factory('BasicService', function($http){
        var some_arg = 'abcd'
        var BasicService = {
            method_one: function(arg=some_arg){ /*code for method one*/},
            method_two: function(arg=some_arg){ /*code for method two*/},
            method_three: function(arg=some_arg){ /*code for method three*/},
        });
        return BasicService;
    }   
);
Run Code Online (Sandbox Code Playgroud)

现在我想定义一个从上面扩展的扩展服务,BasicService以便我可以使用我的扩展服务在BasicService下定义的方法.也许是这样的:

    factory('ExtendedService', function($http){
        var ExtendedService = BasicService();
        ExtendedService['method_four'] = function(){/* code for method four */}
        return ExtendedService;
    }
Run Code Online (Sandbox Code Playgroud)

javascript angularjs

32
推荐指数
3
解决办法
2万
查看次数

获取具有数组中某些属性的项的计数

我有一个对象数组如下.

$scope.students = [{'isSelected': true},
    {'isSelected': true},
    {'isSelected': false},
    {'isSelected': true},
    {'isSelected': true},
]
Run Code Online (Sandbox Code Playgroud)

如何获取isSelected属性设置为的计数项true

更新:

问题是$scope.students从REST api获取并简单地循环遍历$ scope.students变量不起作用,undefined直到请求完成,因此循环代码错误说出来$scope.students is not defined.

我尝试过使用$watch但在这种情况下我必须在watch指令下定义循环,它只在$ scope.students定义时才有效,之后循环不起作用$ scope.students本身没有改变.

javascript angularjs

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

Django测试 - 检查重定向视图的消息

我一直在为我的一个django应用程序编写测试,并且一直在寻找解决这个问题已有一段时间了.我有一个视图,使用django.contrib.messages不同的情况发送消息.该视图类似于以下内容.

from django.contrib import messages
from django.shortcuts import redirect

import custom_messages

def some_view(request):
    """ This is a sample view for testing purposes.
    """

    some_condition = models.SomeModel.objects.get_or_none(
        condition=some_condition)
    if some_condition:
        messages.success(request, custom_message.SUCCESS)
    else:
        messages.error(request, custom_message.ERROR)
    redirect(some_other_view)
Run Code Online (Sandbox Code Playgroud)

现在,在测试此视图client.get的响应时,不包含context包含messages该视图的字典,因为此视图使用重定向.对于渲染模板的视图,我们可以使用访问消息列表messages = response.context.get('messages').我们如何获得messages重定向视图的访问权限?

testing django redirect messages django-context

23
推荐指数
2
解决办法
6505
查看次数

比较django TestCase中的查询集

我有一个非常简单的观点如下

def simple_view(request):
    documents = request.user.document_set.all()
    return render(request, 'simple.html', {'documents': documents})
Run Code Online (Sandbox Code Playgroud)

为了在我的测试用例中测试上面的视图,我有以下方法出错.

Class SomeTestCase(TestCase):
    # ...
    def test_simple_view(self):
        # ... some other checks
        docset = self.resonse.context['documents']
        self.assertTrue(self.user.document_set.all() == docset) # This line raises an error
    # ...
Run Code Online (Sandbox Code Playgroud)

我得到的错误是AssertionError: False is not true.我尝试打印两个查询集,两者完全相同.False当两个对象相同时,为什么会返回?有任何想法吗 ?

目前为了克服这一点,我使用了一个讨厌长度的讨厌的黑客如下:

ds1, ds2 = self.response.context['documents'], self.user.document_set.all()
self.assertTrue(len([x for x in ds1 if x in ds2]) == len(ds1) == len(ds2)) # Makes sure each entry in ds1 exists in ds2
Run Code Online (Sandbox Code Playgroud)

django compare django-queryset testcase

18
推荐指数
2
解决办法
8504
查看次数

批量更新多个字段

我有两个型号如下:

class Book(models.Model):
    title = models.CharField(max_length=100)
    year = models.IntegerField(max_lenght=4)
    author = models.ManyToManyField(null=true, blank=true)


class Author(models.CustomUser):
    # some fields
Run Code Online (Sandbox Code Playgroud)

现在,我要做的是添加一个Author多个Book对象而不迭代书对象列表.

Django的更新方法不支持ManyToManyField文档.它说

您只能使用此方法设置非关系字段和ForeignKey字段.要更新非关系字段,请将新值作为常量提供.要更新ForeignKey字段,请将新值设置为要指向的新模型实例.

所以目前我正在做以下事情,这是非常低效的,因为我将为每个图书对象访问数据库.

author = Author.objects.get(pk=1)
books = Book.objects.filter(**kwargs) # say this returns 100 objects
# each loop here will hit the database making it really inefficient
# for long lists.
for book in books:
    book.authors.add(author)
    book.save()
Run Code Online (Sandbox Code Playgroud)

我很确定有一种解决方法,但我无法在文档中找到它.任何帮助,将不胜感激.谢谢

django many-to-many bulk

18
推荐指数
2
解决办法
9162
查看次数

将其他参数传递给post_save信号

嘿,我的django应用程序中有一个用户注册表,它在用户尝试注册时收集其他数据,如地址,城市,国家,电话号码等.

此数据通过post_save信号保存在Account模型类中.用户创建过程如下所示:

# Function to Create user Account/Profile
def create_user_account(sender, instance, created, **kwargs):
    if created:
      models.Account.objects.create(user=instance)

# Create User / User Registration
def UserRegistration(request):
    if request.method == 'POST':
        username = request.POST['fn'].capitalize() + ' ' + request.POST['ln'].capitalize()
        # CREATE USER
        newuser = User.objects.create_user(username=username, email=request.POST['email'], password=request.POST['pw'])
        newuser.first_name = request.POST['fn'].capitalize()
        newuser.last_name = request.POST['ln'].capitalize()
        newuser.save()
    return HttpResponse(username)

#Post Save handler to create user Account/Profile
post_save.connect(create_user_account, sender=User)
Run Code Online (Sandbox Code Playgroud)

这里UserRegistration函数在用户发布表单时调用,在此函数下我可以获取POST数据,我想要的是将该数据传递给create_user_account方法,以便填充Account模型中的字段.

现在我确实看到在数据库中创建了帐户对象,但除用户字段之外的所有字段都是空的.显然,因为POST变量没有传递给create_user_account方法.

python django

17
推荐指数
1
解决办法
7389
查看次数

如何将call_command与dumpdata命令一起使用以将json保存到文件中

我试图使用该call_command方法来调用dumpdata command.手动,我按如下方式使用它将数据保存到文件中.

python manage.py dumpdata appname_one appname_two > /path/to/save/file.json
Run Code Online (Sandbox Code Playgroud)

它保存了json文件.现在,我处于需要使用该call_command方法调用此命令的情况.

我可以使用以下命令从命令打印出json:

from django.core.management import call_command

call_command('dumpdata', 'appname_one', 'appname_two')
Run Code Online (Sandbox Code Playgroud)

有没有办法可以将给定的数据保存到文件中,就像我们从命令行那样做?

django json command call dumpdata

14
推荐指数
2
解决办法
9697
查看次数