django模型对象和queryset保存到其他表

时间:2018-05-29 06:30:18

标签: python django django-models django-rest-framework

使用django 2.0.2 python3.4

跳过详细信息models.py

class Post(models.Model):
    postuid = models.BigAutoField(
        db_column='postUID', primary_key=True)
    useruid = models.Foreignkey .... skip
    content = models.Text       .... 
    registerdate = models.Date  ....

class KeepPost(models.Model):
    keeppostuid =  models.BigAutoField(
    db_column='KeepPostUID', primary_key=True)
    useruid = models.ForeignKey(
    'Userinfo', db_column='UserUID', on_delete=models.CASCADE)
    postuid =  models.ForeignKey(
    'Post', db_column='PostUID', on_delete=models.DO_NOTHING) 
    content = models.TextField(db_column='Content')
    registerdate = models.DateTimeField(
    db_column='RegisterDate')
    keepdate = models.DateTimeField(
    db_column='KeepDate')

class ReportPost(models.Model):
    reportuid=models.BigAutoField(
    db_column='ReportUID', primary_key=True)
    postuid=models.ForeignKey(
    'Post', db_column='PostUID', on_delete=models.DO_NOTHING) 
    #useruid is reporter
    useruid=models.ForeignKey(
    'Userinfo', db_column='UserUID', on_delete=models.CASCADE)
    registerdate = models.DateTimeField(
    db_column='RegisterDate'

PostKeepPost

Post.objects.get(postuid=1) or Post.objects.filter(useruid=1)
KeepPost.objects.create(modelobjects or queryset) 

get()是返回模型对象,filter()是返回查询集

如果我想在报告后删除

为什么要使用on_delete DO_NOTHING - >即使ReportedPost被删除,我也希望保留记录

只删了一个帖子 前)

postmodel = Post.objects.get(postuid=request.get("postuid"))

希望模型转移到KeepPost并删除

postmodel.delete()

如果用户想要删除帐户

usermodel = User.objects.get(useruid=useruid)
Postquery = usermodel.post_set.all()
reportPost = ReportPost.objects.filter(Q(postuid__in=Postquery))

我认为在交叉Postquery和reportPost之后转移到KeepPost

usermodel.delete()

1 个答案:

答案 0 :(得分:1)

以下是我可能会做的事情。

<强> 1。移除KeepPost模型。

<强> 2。更改帖子模型

class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
    content = models.TextField() 
    registerdate = models.DateTimeField(auto_now_add=True)
    is_archived = models.BooleanField(default=False)
    archived_date = models.DateTimeField()

    @property
    def archive_post(self):
        if not self.is_archived:
            self.is_archived = True
            self.archived_date = datetime.now()
            self.save()

这里发生了什么?

  1. 首先,您不需要KeepPost模型,因为删除并保留Post对象仍然会维护数据。
  2. 已移除postuid = models.BigAutoField(db_column='postUID', primary_key=True)。 Django将自动分配主键ID。
  3. 添加is_archivedarchived_date最简单的方法是保留实例根本不删除它。
  4. 现在在您的视图中,您可以简单地使用它,或者从单个实例或查询集获取源代码。

    post = Post.objects.get(pk=1) # or id=1
    post.archive_post
    

    OR

    posts = Post.objects.filter(user_id=1)
    
    for post in posts:
        post.archive_post
    

    如果您想永久删除Post个实例,请调用.delete()方法。