[英]Unary relationship flask sqlalchemy
I have a model that I created to store users comments, and because of the nature of comments sections in apps I tried to create my model it in a way such that comments can be under other comments, so I tried to use a unary relationship on the comments model我创建了一个 model 来存储用户评论,由于应用程序中评论部分的性质,我尝试以一种方式创建我的 model,以便评论可以在其他评论之下,所以我尝试使用一元关系评论 model
class Comments(db.Model):
id = db.Column(db.Integer, primary_key=True)
comment = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
user = db.relationship("User", backref=db.backref("comment", lazy=True))
meme_id = db.Column(db.Integer, db.ForeignKey("memedata.meme_id"), nullable=False)
meme = db.relationship("MemeData", backref=db.backref("comment"), lazy=True)
parent_comment_id = db.Column(db.Integer, db.ForeignKey("comments.id"), nullable=True)
parent_comment = db.relationship("Comments")
where the parent_comment
is a recursive relationship to the model and parent_comment_id
is the id of the parent comment.其中
parent_comment
是与 model 的递归关系, parent_comment_id
是父评论的 id。 My problem is it doesn't work how I expect it to work.我的问题是它无法按我期望的那样工作。
Basically if the comment has no parent comment (not under any comment) then I pass in Null
but when I try to store a comment that has a parent comment (under another comment), it overwrites the parent_comment_id
for the PARENT COMMENT to that of the child comment and leaves the CHILD COMMENT parent_comment_id
as NULL
基本上,如果评论没有父评论(不在任何评论下),那么我传入
Null
但是当我尝试存储具有父评论的评论(在另一个评论下)时,它会将 PARENT COMMENT 的parent_comment_id
覆盖为子评论并将 CHILD COMMENT parent_comment_id
为NULL
Example, we have an initial comment in the database that has no comment under it例如,我们在数据库中有一个初始评论,它下面没有任何评论
id | comment | user_id | meme_id | parent_comment_id
1 | blah... | 1 | 3 | NULL
assuming I want to store a comment under this I would do something like假设我想在此下存储评论,我会做类似的事情
parent=Comments.query.get(1)
comment = Comments(
comment="another comment",
user=user,
meme=meme,
parent_comment=[parent]
)
Now what I would expect is...现在我期望的是...
id | comment | user_id | meme_id | parent_comment_id
1 | blah... | 1 | 3 | NULL
2 | another... | 5 | 3 | 1
...however what I get is ...但是我得到的是
id | comment | user_id | meme_id | parent_comment_id
1 | blah... | 1 | 3 | 2
2 | another... | 5 | 3 | NULL
I would appreciate any comment or method on how I can get my desired result我将不胜感激关于如何获得我想要的结果的任何评论或方法
You specified您指定的
parent_comment=[parent]
It looks like what you want is just an integer:看起来你想要的只是一个 integer:
parent_comment=parent.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.