复制Django模型实例,包括其所有关系

时间:2015-10-16 17:19:48

标签: javascript python django python-3.x copy

在开始我的项目后,我正在使用简单的博客与django和python3一起玩。

事情是这样的。我有一个模特。

class Post(models.Model):
  post_text = models.TextField()
  post_likes = models.BigIntegerField()
  post_author = models.ForeignKey(User)
  pub_date = models.DateTimeField('date published')

class Comments(models.Model):
  post = models.ForeignKey("Post")
  comment= models.TextField(max_length=100) 

我需要在我的视图中从这两个元素中复制一份。我正在使用此代码。

def duplicate(request):
    post_id = request.POST.get('post_id')
    post = Post.objects.get(id = post_id)
    new_post = deepcopy(post)
    post.id = None 
    post.save()
    response_data = {}   
    return HttpResponse(
       json.dumps(response_data),
       content_type="application/json"
    )

javascript。

$(function() {
 function create_post() {
console.log("create post is working!") // sanity check
$.ajax({
    url : "add_post/",
    type : "POST",
    data : { post_text: $('#text_area').val()},
    success : function(json) {
        $('#text_area').val(''); // remove the value from the input
        console.log(json); // log the returned json to the console       
        $("#posts").append("<tr><td class='card'>"+json.id+"</td><td>"+json.author+"</td><td>"+json.text+"</td><td class='remove-post-button'><button>Borrar</button></td><td class='duplicar'><button onClick='window.location.reload()'>Duplicar</button></td>");            
        console.log("success"); // another sanity check
    },
    // handle a non-successful response
    error : function(xhr,errmsg,err) {
        $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
            " <a href='#' class='close'>&times;</a></div>");
        console.log(xhr.status + ": " + xhr.responseText);
    }
});

}

但它只能从我的班级制作副本&#34; Post&#34;具有所有属性。

我的观点是。

<tbody id='posts'>
{% for post in posts %}
    <tr class="post-card" data-post-id="{{ post.id }}">
    <td>{{ post.id }}</td>
    <td class="post-author">{{ post.post_author }}</td>
    <td class="post-content">{{ post.post_text }}</td>
    {% for comment post.comments_set.all %}
    <td class="post-comments">{{comment.comments}}</td>
    {%endfor%}
    <td class="remove-post-button"><button>Borrar</button></td>
    <td class="duplicar"><button onClick='window.location.reload()'>Duplicar</button></td>
    </tr>
{% endfor %}

如何从帖子和评论中复制并在视图中显示?

1 个答案:

答案 0 :(得分:0)

来自Django docs

  

此过程不会复制相关对象。如果要复制关系,则必须编写更多代码。

但要小心,因为Django docs中给出的示例适用于ManyToMany字段。这里有一个ForeignKey,所以你必须这样做:

def duplicate(request):
    post_id = request.POST.get('post_id')
    post = Post.objects.get(id=post_id)
    old_comments = post.comment_set.all()
    # copy Post instance
    new_post = post
    post.pk = None 
    post.save()
    # and now we copy all comments
    [post.comment_set.add(comment) for comment in old_comments]
    response_data = {}   
    return HttpResponse(json.dumps(response_data), content_type="application/json")