在Django Rest FrameWork中'many = True'是做什么的?

时间:2018-07-07 12:58:51

标签: django django-rest-framework

我现在正在学习DRF,对此-(void)postOnTwitter{ STTwitterAPI *twitter = [STTwitterAPI twitterAPIWithOAuthConsumerName:nil consumerKey:kOAuthConsumerKey consumerSecret:kOAuthConsumerSecret]; [twitter postReverseOAuthTokenRequest:^(NSString *authenticationHeader) { NSLog(@"**AuthenticationHeader :%@", authenticationHeader); STTwitterAPI *twitterAPIOS = [STTwitterAPI twitterAPIOSWithFirstAccount]; [twitterAPIOS verifyCredentialsWithUserSuccessBlock:^(NSString *username, NSString *userID) { NSLog(@"**username :%@ **userID :%@", username,userID); [twitterAPIOS postReverseAuthAccessTokenWithAuthenticationHeader:authenticationHeader successBlock:^(NSString *oAuthToken, NSString *oAuthTokenSecret, NSString *userID, NSString *screenName) { STTwitterAPI *x = [STTwitterAPI twitterAPIWithOAuthConsumerName:nil consumerKey:kOAuthConsumerKey consumerSecret:kOAuthConsumerSecret oauthToken:oAuthToken oauthTokenSecret:oAuthTokenSecret]; [x verifyCredentialsWithUserSuccessBlock:^(NSString *username, NSString *userID) { NSLog(@"**User name :%@", username); [x getDirectMessagesSinceID:nil count:10 successBlock:^(NSArray *messages) { // ... NSLog(@"**messages :%@", messages); } errorBlock:^(NSError *error) { NSLog(@"**error :%@", error); // ... }]; } errorBlock:^(NSError *error) { NSLog(@"**error1 :%@", error); // ... }]; } errorBlock:^(NSError *error) { NSLog(@"**error2 :%@", error); // ... }]; } errorBlock:^(NSError *error) { NSLog(@"**error3 :%@", error); }]; } errorBlock:^(NSError *error) { NSLog(@"**error4 :%@", error); }]; 代码有点困惑。它有什么作用?还是什么意思?

示例1

many = True

示例2

class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.RelatedField(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

1 个答案:

答案 0 :(得分:4)

我认为您正在将many=True与多对多混淆,但是概念并非如此

通过设置many=True,您告诉drf queryset包含多个项目(项目列表),因此drf需要使用序列化程序类序列化每个项目(而serializer.data将是一个列表)

如果不设置此参数,则表示queryset是单个实例,serializer.data将是单个对象)