I have a Table called property that accepts a contains column which refers to propertyContains table, then propertyContains will have a media column which refers to media table. i have no idea if i am storing the images the right way and i am wondering if there is any better/more efficient ways.
my code
class Property(Base):
__tablename__ = "property"
property_id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("propertyOwner.user_id"))
title = Column(String)
description = Column(String)
Location = Column(String)
rented = Column(Boolean)
rented_by = Column(Integer, ForeignKey("client.client_id"))
contains = relationship("PropertyContains", back_populates="contains_owner")
owner = relationship("Owner", back_populates="properties")
date = Column(Date, default=func.now())
class Config:
arbitrary_types_allowed = True
class Media(Base):
__tablename__ = "media"
media_id = Column(Integer, unique=True, primary_key=True, index=True)
media1 = Column(LargeBinary)
media2 = Column(LargeBinary)
media3 = Column(LargeBinary)
media_owner = Column(Integer, ForeignKey('propertyContains.property_contains_id', ondelete="CASCADE"))
class Config:
arbitrary_types_allowed = True
class PropertyContains(Base):
__tablename__ = "propertyContains"
property_contains_id = Column(Integer, unique=True, primary_key=True, index=True)
property_id = Column(Integer, ForeignKey("property.property_id"))
# media_id = Column(Integer, ForeignKey("media.media_id"))
bed_rooms = Column(Integer)
media = relationship("Media", backref="media", passive_deletes=True)
contains_owner = relationship("Property", back_populates="contains")
class Config:
arbitrary_types_allowed = True
please keep in note that i am a beginner <3.
Related
I need to create four tables. First table include the "Users", second include "Group Name", the second table should be related to "Users" table. Third table include "Groups Columns Data" which is related to "Group" table, and finally the fourth table is "Group Borrow Lending Data" which is also linked to third table i.e "Groups".
But it's throwing an error when I try to get specific username.
TypeError: sqlalchemy.exc.InvalidRequestError: Can't compare a
collection to an object or collection; use contains() to test for
membership.
#v1.get("/get-specific-groups/{group_name}", tags=["GROUP"])
def get_specific_groups(group_name: str, current_user: CreateGroupSchema = Depends(get_current_user), db: Session = Depends(get_db)):
return db.query(User, Group, GroupColumnsData).join(GroupColumnsData).filter(Group.owner_username == current_user.get("username")).all()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String(60), unique=True, nullable=False)
email = Column(String(80), unique=True, nullable=False)
password = Column(String(140), nullable=False)
groups = relationship("Group", backref="owner")
class Group(Base):
__tablename__ = "groups"
id = Column(Integer, primary_key=True, index=True)
group_name = Column(String(60), unique=True, nullable=False)
description = Column(String, nullable=False)
owner_username = Column(String, ForeignKey("users.username"), default=User.username)
group_username = relationship("GroupColumnsData", backref="group_owner")
class GroupColumnsData(Base):
__tablename__ = "groupsColumnsData"
id = Column(Integer, primary_key=True, index=True)
payee_name = Column(String(60))
item_name = Column(String(100))
amount_spent = Column(Integer)
owner_group = Column(String, ForeignKey("groups.group_name"), default=Group.group_name)
class GroupBorrowLendingData(Base):
__tablename__ = "groupsBorrowLendingData"
id = Column(Integer, primary_key=True, index=True)
lender = Column(String(60))
money_borrowed = Column(Integer)
borrower = Column(String(60))
owner_group = Column(String, ForeignKey("groups.group_name"), default=Group.group_name)
The Following code worked!
#v1.get("/get-specific-groups/{group_name}", tags=["GROUP"])
def get_specific_groups(group_name: str, current_user: CreateGroupSchema = Depends(get_current_user), db: Session = Depends(get_db)):
return db.query(Group).filter(Group.owner_username == current_user.get("username")).filter(Group.group_name.match(group_name)).all()
Table is this
class CustomGroups(Base):
__tablename__ = 'custom_groups'
id = Column(Integer, primary_key=True)
name = Column(String(80), unique=True, nullable=False)
last_used = Column(DateTime, default=datetime.utcnow())
created = Column(DateTime, default=datetime.utcnow())
images = relationship("Images", secondary=images_with_groups, back_populates="groups")
tags = relationship("Tags", secondary=custom_groups_with_tags, back_populates="groups")
children = relationship("CustomGroups", secondary='custom_groups_relationship',
primaryjoin='CustomGroups.id==CustomGroupsRelationship.parent_id',
secondaryjoin="CustomGroups.id==CustomGroupsRelationship.child_id",
backref="parent")
Relationship table
class CustomGroupsRelationship(Base):
__tablename__ = 'custom_groups_relationship'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('custom_groups.id'))
child_id = Column(Integer, ForeignKey('custom_groups.id'))
created_at = Column(DateTime, default=datetime.now())
updated_at = Column(DateTime, default=datetime.now())
I want to have UniqueConstraint on CustomGroups.name and CustomGroups.parent at sametime.
But also when they are on same level, there shouldn't be duplicate names, similar to windows folder structure.
Thanks
I've been working on a local Sports Fantasy app. The app allows each team to include 8 players where a player can be in more than one team. I've created a table inside the database for player's information and another table for team's information. I want a way to connect a team row to multiple player rows.
My current code:
class Player(Base):
__tablename__ = 'player'
id = Column(Integer, primary_key=True)
name = Column(String(32), index=True, nullable=False)
price = Column(Integer)
position = Column(String(32))
picture = Column(String(32), index=True)
class PlayerStatus(Base):
__tablename__ = 'player_status'
id = Column(Integer, primary_key=True)
player_id = Column(Integer, ForeignKey('player.id'))
round = Column(Integer)
goals = Column(Integer, default=0)
assists = Column(Integer, default=0)
clean_sheet = Column(Integer, default=0)
saves = Column(Integer, default=0)
bonus = Column(Integer, default=0)
minutes_played = Column(Integer, default=0)
goals_conceded = Column(Integer, default=0)
player = relationship(Player)
class Team(Base):
__tablename__ = 'team'
id = Column(Integer, primary_key=True)
name = Column(String(64))
user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
gk_id = Column(Integer, ForeignKey('player.id'))
defender_1_id = Column(Integer, ForeignKey('player.id'))
defender_2_id = Column(Integer, ForeignKey('player.id'))
mid_1_id = Column(Integer, ForeignKey('player.id'))
mid_2_id = Column(Integer, ForeignKey('player.id'))
mid_3_id = Column(Integer, ForeignKey('player.id'))
attack_1_id = Column(Integer, ForeignKey('player.id'))
attack_2_id = Column(Integer, ForeignKey('player.id'))
total_points = Column(Integer)
player = relationship(Player)
user = relationship(User)
I am asking fask_sqlalchemy to create table for me. But I am getting a NoReferencedTable Error.
Here is the code for Models:
from db import db
class Artist(db.Model):
__tablename__ = 'artists'
ArtistId = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.NVARCHAR(120))
class Album(db.Model):
___tablename__ = 'albums'
AlbumId = db.Column(db.Integer, primary_key=True)
Title = db.Column(db.NVARCHAR(160), nullable=False)
ArtistId = db.Column(db.ForeignKey('artists.ArtistId'), nullable=False, index=True)
artist = db.relationship('Artist')
class Employee(db.Model):
__tablename__ = 'employees'
EmployeeId = db.Column(db.Integer, primary_key=True)
LastName = db.Column(db.NVARCHAR(20), nullable=False)
FirstName = db.Column(db.NVARCHAR(20), nullable=False)
Title = db.Column(db.NVARCHAR(30))
ReportsTo = db.Column(db.ForeignKey('employees.EmployeeId'), index=True)
BirthDate = db.Column(db.DateTime)
HireDate = db.Column(db.DateTime)
Address = db.Column(db.NVARCHAR(70))
City = db.Column(db.NVARCHAR(40))
State = db.Column(db.NVARCHAR(40))
Country = db.Column(db.NVARCHAR(40))
PostalCode = db.Column(db.NVARCHAR(10))
Phone = db.Column(db.NVARCHAR(24))
Fax = db.Column(db.NVARCHAR(24))
Email = db.Column(db.NVARCHAR(60))
parent = db.relationship('Employee', remote_side=[EmployeeId])
class Genre(db.Model):
__tablename__ = 'genres'
GenreId = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.NVARCHAR(120))
class MediaType(db.Model):
__tablename__ = 'media_types'
MediaTypeId = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.NVARCHAR(120))
class Playlist(db.Model):
__tablename__ = 'playlists'
PlaylistId = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.NVARCHAR(120))
tracks = db.relationship('Track', secondary='playlist_track')
class Customer(db.Model):
__tablename__ = 'customers'
CustomerId = db.Column(db.Integer, primary_key=True)
FirstName = db.Column(db.NVARCHAR(40), nullable=False)
LastName = db.Column(db.NVARCHAR(20), nullable=False)
Company = db.Column(db.NVARCHAR(80))
Address = db.Column(db.NVARCHAR(70))
City = db.Column(db.NVARCHAR(40))
State = db.Column(db.NVARCHAR(40))
Country = db.Column(db.NVARCHAR(40))
PostalCode = db.Column(db.NVARCHAR(10))
Phone = db.Column(db.NVARCHAR(24))
Fax = db.Column(db.NVARCHAR(24))
Email = db.Column(db.NVARCHAR(60), nullable=False)
SupportRepId = db.Column(db.ForeignKey('employees.EmployeeId'), index=True)
employee = db.relationship('Employee')
class Invoice(db.Model):
__tablename__ = 'invoices'
InvoiceId = db.Column(db.Integer, primary_key=True)
CustomerId = db.Column(db.ForeignKey('customers.CustomerId'), nullable=False, index=True)
InvoiceDate = db.Column(db.DateTime, nullable=False)
BillingAddress = db.Column(db.NVARCHAR(70))
BillingCity = db.Column(db.NVARCHAR(40))
BillingState = db.Column(db.NVARCHAR(40))
BillingCountry = db.Column(db.NVARCHAR(40))
BillingPostalCode = db.Column(db.NVARCHAR(10))
Total = db.Column(db.Numeric(10, 2), nullable=False)
customer = db.relationship('Customer')
class Track(db.Model):
__tablename__ = 'tracks'
TrackId = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.NVARCHAR(200), nullable=False)
AlbumId = db.Column(db.ForeignKey('albums.AlbumId'), index=True)
MediaTypeId = db.Column(db.ForeignKey('media_types.MediaTypeId'), nullable=False, index=True)
GenreId = db.Column(db.ForeignKey('genres.GenreId'), index=True)
Composer = db.Column(db.NVARCHAR(220))
Milliseconds = db.Column(db.Integer, nullable=False)
Bytes = db.Column(db.Integer)
UnitPrice = db.Column(db.Numeric(10, 2), nullable=False)
album = db.relationship('Album')
genre = db.relationship('Genre')
media_type = db.relationship('MediaType')
class InvoiceItem(db.Model):
__tablename__ = 'invoice_items'
InvoiceLineId = db.Column(db.Integer, primary_key=True)
InvoiceId = db.Column(db.ForeignKey('invoices.InvoiceId'), nullable=False, index=True)
TrackId = db.Column(db.ForeignKey('tracks.TrackId'), nullable=False, index=True)
UnitPrice = db.Column(db.Numeric(10, 2), nullable=False)
Quantity = db.Column(db.Integer, nullable=False)
invoice = db.relationship('Invoice')
track = db.relationship('Track')
The errror that I get is
sqlalchemy.exc.NoReferencedTableError
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with
column 'tracks.AlbumId' could not find table 'albums' with which to
generate a foreign key to target column 'AlbumId'
The albums table is there and it has AlbumId column as well.
I don't understand this error.
Need some help understanding what is causing this error.
i think you made a mistake in your Album class. You can't have
db.relationship(...)
and
db.Column(db.ForeignKey(...))
in the same class.
I think, your Artist and Album classes should look like this:
class Artist(db.Model):
__tablename__ = 'artists'
ArtistId = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.NVARCHAR(120))
Albums = db.relationship('Album', backref="artist"))
# Instead of 'Albums', you can name it whatever you want.
# It's just a way to access albums from an artist.
class Album(db.Model):
___tablename__ = 'albums'
AlbumId = db.Column(db.Integer, primary_key=True)
Title = db.Column(db.NVARCHAR(160), nullable=False)
ArtistId = db.Column(db.ForeignKey('artists.ArtistId'), nullable=False, index=True)
Thanks to this, you will be able to access albums from an artist within the Artiste class and vice-versa.
Thereby, if you want to access albums from an artist, you can do something like this:
artist = Artist(...)
artist.Albums
# It will automatically return albums from this artist
and vice-versa.
I suggest you to watch these two videos :
https://www.youtube.com/watch?v=juPQ04_twtA (One-to-Many relationship)
https://www.youtube.com/watch?v=OvhoYbjtiKc (Many-to-Many relationship)
In my schema, a Hardware item may have zero or more Mods recorded against it. I'm trying to filter a query based on an exact match against a list of mods. For example, I might want to filter for Hardware which has mods [2,3,5], and no others.
At the moment, I'm grouping and counting to check that the number of mods is correct, then adding a filter in a for loop to match the exact mod numbers:
...
query = query.join(Hardware).join(Mod)
query = query.group_by(Tag.tag_id).having(len(v['m']) == func.count(Mod.mod_number))
for m in v['m']:
query = query.filter(Hardware.mods.any(mod_number=m))
...
Is there a better way to express this using SQLAlchemy? In particular, the documentation recommends against using func.count() because it fails in some corner cases..
My schema looks like this:
Base = declarative_base()
class Tag(Base):
__tablename__ = 'tag'
tag_id = Column(Integer, primary_key=True)
order_code = Column(String, nullable=False)
version = Column(String, nullable=False)
status = Column(String, nullable=False)
comments = Column(String)
software = relationship(
"Software",
backref="tag",
collection_class=attribute_mapped_collection('artefact'),
)
hardware = relationship(
"Hardware",
backref="tag",
collection_class=attribute_mapped_collection('artefact'),
)
__table_args__ = (
UniqueConstraint('order_code', 'version'),
)
def as_dict(self):
d = as_dict_columns(self)
d['software'] = {s: as_dict_columns(self.software[s]) for s in self.software}
d['hardware'] = {h: self.hardware[h].as_dict() for h in self.hardware}
return d
class Software(Base):
__tablename__ = 'software'
software_id = Column(Integer, primary_key=True)
tag_id = Column(String, ForeignKey('tag.tag_id'))
artefact = Column(String, nullable=False)
version = Column(String, nullable=False)
__table_args__ = (
UniqueConstraint('tag_id', 'artefact'),
)
def __str__(self):
""" This is to deal with Jinja2/SQLAlchemy wackiness """
return self.version
class Hardware(Base):
__tablename__ = 'hardware'
hardware_id = Column(Integer, primary_key=True)
tag_id = Column(String, ForeignKey('tag.tag_id'))
product_id = Column(String, nullable=True)
artefact = Column(String, nullable=False)
version = Column(String, nullable=False)
mods = relationship("Mod", backref="hardware")
__table_args__ = (
UniqueConstraint('tag_id', 'product_id'),
)
def as_dict(self):
d = as_dict_columns(self)
d['mods'] = self.__list_mods__()
return d
class Mod(Base):
__tablename__ = 'mod'
hardware_id = Column(String, ForeignKey('hardware.hardware_id'), primary_key=True)
mod_number = Column('mod_number', Integer, primary_key=True, nullable=False)
__table_args__ = (
UniqueConstraint('hardware_id', 'mod_number'),
)