A
A
Alexey_vip2022-02-14 19:18:37
Python
Alexey_vip, 2022-02-14 19:18:37

How to configure many to many on flask?

One tag always returns only the first image, instead of all the images that were associated with this tag

tags = db.Table("tags",
            db.Column("img_id", db.Integer, db.ForeignKey("bimg.id")),
            db.Column("tag_id", db.Integer, db.ForeignKey("tag.id")),
            )


class Bimg(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    lib = db.Column(db.String(500))
    name = db.Column(db.String(500), nullable=True)
    webp = db.Column(db.String(500), nullable=True)
    date = db.Column(db.DateTime, default=datetime.utcnow)
    tags = db.relationship("Tag", secondary=tags, backref="posts")

    def __repr__(self):
        return "<Bimg %r>" % self.id


class Tag(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(5000), nullable=True)

    def __repr__(self):
        return "<Tag %r>" % self.name


#Загрузка файлов и получение тегов
    @application.route("/upload", methods=["POST", "GET"])
def upload():
    if request.method == "POST":
        f = request.files["file"]
        tag = request.form["tags"].split(",")
        c= "static/images/rz/"
        f.save(f"{c}" + f.filename)
        name = f.filename.split(".")[0]
        sa = Image.open(f"{c}" + f.filename)
        sa.save(f"{c}m/{name}.webp")
        webp = name + ".webp"
        save_db = Bimg(name=f.filename, lib=c, webp=webp)
        for i in tag:
            tags = Tag(name = i)
            save_db.tags.append(tags)
            db.session.add(save_db)
        db.session.commit()
        return render_template("/upload.html")
    else:
        return render_template("/upload.html")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Popov, 2022-02-17
@Alexey_vip

You create a new tag every time, even if it exists with the same name
tags = Tag(name = i)
. Accordingly, it is attached to the image.
1) Make a unique field for the tag name (so that they do not multiply):

class Tag(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(5000), unique=True, nullable=True)

2) When adding tags to an image, look for the existing one first:
...
tag = Tag.query.filter_by(name=i).first()  # у вас tags почему-то, хотя это один тег
if not tag:  # если в БД нет тега, то создаём
  tag = Tag(name=i)  # создаём новый тег, если его не нашлось в БД
save_db.tags.append(tag)  # добавляем тег к изображению существующий или только что созданный
...

3) I recommend refactoring the variable names, you confuse yourself)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question