在models.py中:
from django.db import models
...
class Product(models.Model):
...
recommended = models.ManyToManyField('self', blank=True)
...
Run Code Online (Sandbox Code Playgroud)
如果我有一个 Product 查询集,我怎样才能获得所有独特的推荐对象?
例如:产品«A»有3个推荐产品:«B»、«C»和«D»,产品«B»有2个推荐产品:«C»和«E»,在查询集«products»中,我们有«A»和 «B» 产品,在本例中:
# get_products() returns QuerySet of «A» and «B» products
products = get_products().prefetch_related('recommended')
recommended = [item for p in products for item in p.recommended.all()]
Run Code Online (Sandbox Code Playgroud)
我们会得到 [«B», «C», «D», «C», «E»] 的列表,但是如何只得到 [«B», «C», «D», «E»]?
PS当然我们可以在«for»循环中过滤对象,但也许有更有效和公平的方法?...
products = self.request.basket.get_products().prefetch_related(
Prefetch('recommended', queryset=models.Product.objects.distinct()))
recommended_list = [item for p in products for item in p.recommended.all()]
Run Code Online (Sandbox Code Playgroud)
返回:
[<Product: Vestibulum ante …Run Code Online (Sandbox Code Playgroud) 我有几个控制器.在其中一个中,我需要打开Web套接字连接.在另一个我需要监听消息,如果需要更新$ scope.请帮助我在下面的示例中执行此操作:
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.testProp = {};
$scope.testProp2 = '';
// listen messages here
// and update $scope.testProp && $scope.testProp2
}]);
app.controller('SearchCtrl', ['$scope', function($scope) {
// open connection here
}]);
Run Code Online (Sandbox Code Playgroud)
PS我明白这个问题很简单,但我是AngularJS和WebSockets的新手,我需要帮助,现在我没有时间学习文档(后面我会做什么)