Adding a comments field to database with flask/SQLAlchemy?

shadefinale

I'm working on a flask application that has a database that is set up like this like this and am using SQLAlchemy. (display_name was renamed to persona_name since that's what the steam api calls it.)

I'm still in the process of learning how work with databases, and what I have now works fine, I can track all the lists a user has made, and I can get suspects from all lists that one user has made. Also, removing a suspect from the suspect table also seems to remove the suspect from all lists it appears on.

This seems to work well, List and Suspect are classes that inherit from db.Model while suspect_list is an auxiliary table that is not itself a class.

The way it is set up I want to be able to have a suspect show up on multiple lists, but now I want to be able to add comments for individual suspects on individual lists.

I'm not sure how to go about this, but I have a few ideas and am not sure if they work or would have potential downsides.

1) Can I add a comment field to suspect_list?

2) Do I make a comment model as a class that inherits from db.Model and then add it to the auxiliary table instead?

3) Should I create a new id field for the suspect table, make it the primary key instead of steam_id , and then add a comment field so there can be duplicate suspects that have differing comments?

I probably could implement 3 but I don't think it is a good idea because duplicates of the same suspect probably is something that should be avoided.

As for 1 and 2 I don't know if they would work and if they did I'm not sure how to properly implement them.

This is the code that I have for my Models.py if it is needed

My question is how would I properly add comments to this database model I have set up?

Doobeh

Rather then an association table, you really need an association object. Here's a working example.

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.secret_key = 'MOO.'
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite://'  # In memory.
db = SQLAlchemy(app)


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

    def __repr__(self):
        return '<User {}>'.format(self.name)

class Suspect(db.Model):
    __tablename__ = 'suspect'
    id = db.Column(db.Integer, primary_key=True)
    steam_name = db.Column(db.String)

    def __repr__(self):
        return '<Suspect {}>'.format(self.steam_name)

class List(db.Model):
    __tablename__ = 'list'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User', backref=db.backref('lists'))
    suspects = db.relationship('SuspectList', backref='list')
    def __repr__(self):
        return '<List {}>'.format(self.name)


class SuspectList(db.Model):
    __tablename__ = 'suspect_list'
    list_id = db.Column(db.Integer, db.ForeignKey('list.id'), primary_key=True)
    suspect_id = db.Column(db.Integer, db.ForeignKey('suspect.id'), primary_key=True)
    comment = db.Column(db.String)
    suspect = db.relationship('Suspect', backref=db.backref("suspect_list"))

    def __repr__(self):
        return '<SL: %s %s %s>' % (self.list, self.suspect, self.comment)

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
        hacker = Suspect(steam_name='Bob')
        cracker = Suspect(steam_name='Alice')
        carol = User(name='Carol')
        carols_list = List(name='Carols', user=carol)

        hacker_suspect = SuspectList(suspect=hacker, comment='RED HAIR')
        cracker_suspect = SuspectList(suspect=cracker, comment='RED EYES')

        carols_list.suspects.append(hacker_suspect)
        carols_list.suspects.append(cracker_suspect)

        db.session.add(carols_list)  # Trust SQLAlchemy to add all related.
        db.session.commit()

        ## Querying:

        my_list = List.query.filter(User.name == 'Carol').first()
        for record in my_list.suspects:
            print '{} reported {} with comment {}'.format(
                record.list.user.name,
                record.suspect.steam_name,
                record.comment
            )

        # Carol reported Bob with comment RED HAIR
        # Carol reported Alice with comment RED EYES

Two side-notes-- I found it a bit ugly to be use List as a class name, because when you want to query it, your default name would be list = List.query.fi.... which is a bit of a no-go :). Also, what program did you use to generate your ERD?

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Adding fake field value to database query

From Dev

Adding a field to firebase firestore database in Swift

From Dev

Adding name to input field using SQL database field

From Dev

GitHub - LGTM and adding comments

From Dev

adding comments form Django

From Dev

Adding comments to waveform

From

Adding comments to .htaccess

From Dev

Adding id's to comments

From Dev

Adding comments to video with jQuery

From Dev

Adding comments to a JSON file

From Dev

How to include a field in API without adding the key/val in database?

From Dev

updating dataset when adding a new field in database in c#

From Dev

Adding to a database field instead of overwriting it (MySQL UPDATE function)

From Dev

Adding an extra field to all records in Firebase Realtime database

From Dev

Adding the value in database with html inside echo field in phpv

From Dev

Yii2 adding an extra field to the form to add to database

From Dev

Adding a value to a database field that is in your model but is not in your form

From

Implementing Comments and Likes in database

From Dev

Loading comments from Database

From Dev

Firebase comments not appearing on database

From Dev

adding comments using php and html

From Dev

Adding a comments feature for a Project in djangorestframework

From Dev

adding comments to a couchdb design doc

From Dev

Adding comments to endpoints w/ Swagger

From Dev

Adding comments using 'set -x'

From Dev

Adding comments for "<%@" directives in asmx file

From Dev

Ruby on Rails - Adding comments to post

From Dev

Creating comments and adding it into a comment box

From Dev

Database multiple choice and comments structure

Related Related

HotTag

Archive