如何使用Ajax将数据附加到多对多字段?

时间:2019-07-20 10:11:06

标签: django django-rest-framework

我正在尝试使用Ajax更新用户字段。我使用其余框架为用户模型创建了APIView。用户模型包括一个名为“ favorite_entries”的多对多字段,使用下面的代码,我需要事先在JS中获取所有字段数据,并追加新数据并调用放置请求,这对我来说似乎是错误的。

views.py:

class CurrentAuthorView(APIView):
    permission_classes = (permissions.IsAuthenticated, )
    http_method_names = ['get', 'put']

    def put(self, request):
        serializer = AuthorSerializer(request.user, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        serializer = AuthorSerializer(request.user)
        return Response(serializer.data)

javascript:

$("#favorite_entry-btn").on("click", function () {
    let entry_id = $(this).attr("data-entry-id");

    $.ajax({
        url: '/api/v1/author/',
        type: 'PUT',
        data: "favorite_entries=3",
        success: function (data) {
            alert('success');
        },
        error: function (err) {
            console.log(err);
        }
    });

});

我希望在该字段后附加主键“ 3”的条目,但是它将删除所有以前的数据。

1 个答案:

答案 0 :(得分:0)

data属性应该是key:value格式的Javascript对象。

// ========= MODELS =============

const mongoose = require('mongoose');

const { Schema } = mongoose;

const userSchema = new Schema({
    name: { type: String, trim: true, required: true },
    email: { type: String, trim: true, required: true },
    password: { type: String, trim: true, required: true },
    description: { type: String, trim: true, required: true },
    avatar: { type: String, trim: true, required: true },
});

userSchema.virtual('ownerPost', {
  ref: 'Post',
  localField: '_id',
  foreignField: 'userId',
});

const postSchema = new Schema(
  {
    title: { type: String, trim: true, lowercase: true, required: true },
    content: { type: String, required: true },
    summary: {type: String, required: true },
    image: { type: String, trim: true, required: true },
    userId: { type: Schema.Types.ObjectId, ref: 'User', required: true }
  });

const Post = mongoose.model('Post', postSchema);
const User = mongoose.model('User', userSchema);

// ========= CONTROLLERS =============

const getPostById = async (req, res, next) => {
  try {
    const { id } = req.params;
    const post = await Post.findById(id)
      .populate('userId')
      // it doesn't work
      // .select(['title', 'content', 'image', 'userId.name', 'userId.avatar']);
      // it doesn't work
      // .select(['title', 'content', 'image', 'name', 'avatar']);

    return res.status(200).json(post);
  } catch (error) {
    return next(error);
  }
};

// ========= RESPONSE WITHOUT SELECT IN GET POST BY ID =============

{
    "title": "Example Title",
    "content": "<h1>This is content</h1>",
    "summary": "<h4>This is summary</h4>",
    "image": "https://upload.wikimedia.org/wikipedia/commons/0/02/Great_Wave_off_Kanagawa_-_reversed.png",
    "userId": {
        "name": "peter",
        "email": "peter80@gmail.com",
        "password": "$2b$12$LaJWX1/A3ATq4c/tgNIs.uwhnpZGwsqBePFLxIFCDa9gwjitcalda",
        "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
        "avatar": "https://pngimage.net/wp-content/uploads/2018/05/avatar-profile-png-2.png",
        "id": "5e9066e5bc3e6a415134396e"
    },
    "id": "5e90677cbc3e6a4151343970"
}

// ========= RESPONSE WITH SELECT IN GET POST BY ID =============

{
    "title": "titulo de ejemplo",
    "content": "<h1>Esto es un contenido de ejemplo</h1>",
    "image": "https://upload.wikimedia.org/wikipedia/commons/0/02/Great_Wave_off_Kanagawa_-_reversed.png",
    "userId": {
        "name": "peter",
        "email": "peter80@gmail.com",
        "password": "$2b$12$LaJWX1/A3ATq4c/tgNIs.uwhnpZGwsqBePFLxIFCDa9gwjitcalda",
        "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
        "avatar": "https://pngimage.net/wp-content/uploads/2018/05/avatar-profile-png-2.png",
        "id": "5e9066e5bc3e6a415134396e"
    },
    "id": "5e90677cbc3e6a4151343970"
}