Remove a relation many-to-many (association object) on Sqlalchemy

2024/9/25 16:34:47

I'm stuck with a SqlAlchemy problem.

I just want to delete an relation. This relation is made by an association object.

models

class User(db.Model, UserMixin):id                  = db.Column(db.Integer, primary_key=True)email               = db.Column(db.String(255), unique=True)username            = db.Column(db.String(255), unique=True)password            = db.Column(db.String(255))following           = db.relationship('Follower', foreign_keys='Follower.user_id')followed_by         = db.relationship('Follower', foreign_keys='Follower.follow_user_id')def __repr__(self):return '<%s (%i)>' % (self.username, self.id)class Follower(db.Model):__tablename__       = 'followers'user_id             = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)follow_user_id      = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)created_at          = db.Column(db.DateTime, default=datetime.datetime.now)user_followed       = db.relationship("User", primaryjoin=(follow_user_id==User.id))user                = db.relationship("User", primaryjoin=(user_id==User.id))def __repr__(self):return '<%i %i>' % (self.user_id, self.follow_user_id)

How I add a relation (it works !):

u1 = # user 1
u2 = # user 2...f = Follower()
f.user_followed = u2
u1.following.append(f)
db.session.commit()

How I try do delete a relation (it doesn't work):

f = Follower()
f.user_followed = u2u1.following.remove(f)
db.session.commit()

The error

ValueError: list.remove(x): x not in list

I understand why it doesn't work, it's because this Follower() instance is not in the list u1.following. So, how can I delete this relation?

Answer

You can override __eq__, __ne__, and __hash__ so that instances that are not the same instance, but have the same values, compare and hash equal.

I use the following mixin for this purpose. Just override compare_value in the subclass to return whatever should actually be compared.

from sqlalchemy import inspectclass EqMixin(object):def compare_value(self):"""Return a value or tuple of values to use for comparisons.Return instance's primary key by default, which requires that it is persistent in the database.Override this in subclasses to get other behavior."""return inspect(self).identitydef __eq__(self, other):if not isinstance(other, self.__class__):return NotImplementedreturn self.compare_value() == other.compare_value()def __ne__(self, other):eq = self.__eq__(other)if eq is NotImplemented:return eqreturn not eqdef __hash__(self):return hash(self.__class__) ^ hash(self.compare_value())
https://en.xdnf.cn/q/71556.html

Related Q&A

Spark Dataframes: Skewed Partition after Join

Ive two dataframes, df1 with 22 million records and df2 with 2 million records. Im doing the right join on email_address as a key. test_join = df2.join(df1, "email_address", how = right).cach…

Caught TypeError while rendering: __init__() got an unexpected keyword argument use_decimal

While running the program i am getting the following error messageCaught TypeError while rendering: __init__() got an unexpected keyword argument use_decimalHere is my code i am using jquery 1.6.4 d…

How to get chunks of elements from a queue?

I have a queue from which I need to get chunks of 10 entries and put them in a list, which is then processed further. The code below works (the "processed further" is, in the example, just pr…

Receiving commandline input while listening for connections in Python

I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this…

Passing a parameter through AJAX URL with Django

Below is my code. n logs correctly in the console, and everything works perfectly if I manually enter the value for n into url: {% url "delete_photo" iddy=2%}. Alas, when I try to use n as a …

WARNING: toctree contains reference to nonexisting document error with Sphinx

I used the sphinx-quickstart to set everything up. I used doc/ for the documentation root location. The folder containing my package is setup as: myfolder/doc/mypackage/__init__.pymoprob.py...After the…

Removing nan from list - Python

I am trying to remove nan from a list, but it is refusing to go. I have tried both np.nan and nan.This is my code:ztt = [] for i in z:if i != nan:ztt.append(i) zttor:ztt = [] for i in z:if i != np.nan…

Safely unpacking results of str.split [duplicate]

This question already has answers here:How do I reliably split a string in Python, when it may not contain the pattern, or all n elements?(5 answers)Closed 6 years ago.Ive often been frustrated by the…

Get a structure of HTML code

Im using BeautifulSoup4 and Im curious whether is there a function which returns a structure (ordered tags) of the HTML code. Here is an example:<html> <body> <h1>Simple example</h…

max_help_position is not works in python argparse library

Hi colleagues I have the code (max_help_position is 2000):formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=2000) parser = argparse.ArgumentParser(formatter_class=formatter_cl…