2017-07-07 100 views
0

我正在製作我的第一個API,它幾乎是我想要的。我試圖讓用戶既可以單獨訪問,也可以通過他們的組訪問,但我想設置API來顯示用戶明白的所有訪問權限,而不是將其嵌入到組中。合併django-rest-framework結果

基本上,我想取group_affiliation結果並將它們合併到其餘的結果中,因爲它們具有相同的結構,並且在該格式中使用起來更容易。

目前,我的輸出是這樣的:

[ 
    { 
     "username": "admin", 
     "access": [ 
      { 
       "name": "foo" 
      }, 
      { 
       "name": "bar" 
      } 
     ], 
     "group_affiliation": [ 
      { 
       "access": [ 
        { 
         "name": "eggs" 
        }, 
        { 
         "name": "foo" 
        } 
       ], 
      }, 
     ] 
    }, 
] 

但我想它看起來更像是這個,這裏group_affiliation結果合併到其它結果:

[ 
    { 
     "username": "admin", 
     "access": [ 
      { 
       "name": "foo" 
      }, 
      { 
       "name": "bar" 
      }, 
      { 
       "name": "eggs" 
      } 
     ], 
    } 
] 

這裏我的models.py:

class Access(models.Model): 
    name = models.CharField(max_length=100) 
    site_user_access = models.ManyToManyField(User, blank=True) 
    site_group_access = models.ManyToManyField(Group, blank=True) 

這裏是我的serializers.py:

class AccessSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = TopAccess 
     fields = ('name',) 


class GroupSerializer(serializers.ModelSerializer): 
    access = AccessSerializer(
      source='access_set', 
      many=True 
      ) 

    class Meta: 
     model = Group 
     fields = (
       'access', 
       ) 


class UserAccessSerializer(serializers.ModelSerializer): 
    access = AccessSerializer(
      source='access_set', 
      many=True 
      ) 
    group_affiliation = GroupSerializer(
      source='groups', 
      many=True, 
      ) 

    class Meta: 
     model = User 
     fields = (
       'username', 
       'access', 
       'group_affiliation', 
       ) 

任何幫助將不勝感激。

+0

,你究竟有什麼問題,列出所需的結果呢?您需要更具體,並且只包含解釋問題所需的最少量代碼。 [mcve] –

+0

@HåkenLid我試圖將顯示在「group_affiliation」下的結果合併到其他結果中。我編輯了代碼以便它更簡潔 – joedurbak

+1

使用串行器方法字段使您的自定義輸出 –

回答

1

感謝@ zaphod100.10和Betelgeuse V的人們指引我朝着正確的方向以及其他post給我的語法。

這裏是我的解決方案:

class AccessSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Access 
     fields = ('name',) 


class UserAccessSerializer(serializers.ModelSerializer): 
    access = SerializerMethodField('access_set') 

    class Meta: 
     model = User 
     fields = (
       'username', 
       'access', 
       ) 

    def access_set(self, user): 
     queryset = Access.objects.filter(site_user_access=user) 
     queryset = queryset | Access.objects.filter(site_group_access__user=user) 
     queryset = queryset.distinct() 
     serializer = AccessSerializer(instance=queryset, many=True) 
     return serializer.data 

這給上述