Django查询集到没有重复的dicts列表

时间:2016-04-21 10:35:54

标签: django dictionary duplicates django-queryset

我有以下型号

模型

class Player(models.Model):
    name = models.CharField(max_length=50)
    DOB = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return "%s" % self.name


class League(models.Model):
    name = models.CharField(max_length=50)
    country = models.CharField(max_length=50)
    player = models.ForeignKey(Manager, related_name='players')


    def __unicode__(self):
        return "%s" % self.name

视图

def exportdata(request):
    q = League.objects.all().select_related("player")

    content = []
    for record in q:
        info = {
            'players': [record.player.name],
            'leaguename' : record.name,
            'country': record.country
        }
        content.append(info)

    return HttpResponse(json.dumps(content))

响应

[{
    "players": ["Roman"], 
    "leaguename": "La liga",
    "country" : "Spain"
}, 
{
    "players": ["Anthon"], 
    "leaguename": "Premier",
    "country" : "UK"
}, 
{
    "players": ["Xavi"], 
    "leaguename": "La liga",
    "country": "Spain" 
}, 
{
    "players": ["Ronaldo"],
    "leaguename": "Premier ",
    "country": "UK"
},
{
    "players": ["Zessi"],
    "leaguename": "Championship ",
    "country": "Spain"
}
]

我想要以JSON格式在特定联赛(没有重复)中玩的球员列表,所以我可以从角度解析结果。我怎样才能实现这一目标?以下格式的预期答复:

[
    {
        "players": [{"id" : 12,  "name": "Roman"}, {"id" : 150,  "name": "Xavi"}], 
        "leaguename": "La liga (Spain)"
    }, 
    {
        "players": [{"id" : 98,  "name": "Ronaldo"}, {"id" : 9,  "name": "Anthon"}], 
        "leaguename": "Premier (UK)"
    }, 
    {
        "players": [{"id" : 19,  "name": "Zessi"}], 
        "leaguename": "Championship (Spain)"
    }
]

我尝试了什么

def exportdata(request):
    leagues = League.objects.all().select_related("player")

    content = []
    players = []

    for league in leagues:
        # league doesn't exists so append it
        if not any(item['leaguename'] == league.name for item in content):
            content.append({"leaguename": league.name, 
                        "players": players.append({"id": league.player.id, "name": league.player.name})})
        else:
            # league already exists so don't append
            # players doesn't exists so append
            content.append({"leaguename": league.name, 
                        "players": players.append({"id": league.player.id, "name": league.player.name})})


    return HttpResponse(json.dumps(content))

1 个答案:

答案 0 :(得分:0)

def view(request):
    leagues = League.objects.select_related('player')
    results = []
    for league in leagues:
        results.append({'leaguename': league.name,
                        'players': [{'id': player.id, 'name': player.name}
                                    for player in league.players.all()})