SQLAlchemy Foreign Key to different models - sql

I'm currently working on a Flask application and we use SQLAlchemy as ORM. There are two models: Entrie and Comment
class Entry(db.Model):
__tablename__ = 'entries'
id = db.Column(db.Integer, primary_key=True)
....
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key=True)
...
to_id = db.Column(db.Integer, db.ForeignKey('??'))
The problem I am facing is that a comment can be referred to an entry but also to another comment and I don't have a clue how to write such relationships. My first attempt was creating a new class "Comentable" and inherit from this one but I want to find something more sophisticated
Have someone ever been in a similar situation? Any tip will be welcome.
Thanks

Related

How to access a foreign key field in a sqlite model?

I'm working in an auction web app in Django. I'm designing the database and would like to reference the username attribute from User() model in my Listing() model.
class User(AbstractUser):
pass
class Listing(models.Model):
## some fields
owner = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="listing")
def __str__(self):
return f"Owner: #{self.owner.username}"
The User class, in AbstractUser there is a username field, i checked. But somehow I'm getting this error:
'ManyRelatedManager' object has no attribute 'username'

flask sqlalchemy unique constraint not working

I am going through Miguel's awesome flask web development book. I have a question regarding the models.
This is my User model
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' % self.username
In the model, its mentioned that 'username' field is unique, which means this column should have unique values.
Yet i have entries in User model that have the same values.
Here is the snippet from the shell session.
for user in User.query.all():
print user.username
output:
None
None
None
None
None
None
None
None
None
None
None
None
I want to know why it allowed to create entries with username=None multiple times?
Thanks
You have to add clause nullable=False to your username column declaration:
username = db.Column(db.String(64), unique=True, index=True, nullable=False)
DB doesn't take None as a value.

Kohana 3.x ORM has_many through delete relationship

I Have three tables, contact, list and listmembers. Contacts from contact table are associated to lists from list table via listmembers table.
class Model_Contact extends ORM{
protected $_has_many = array(
'lists'=>array('model'=>'List', 'through'=>'listmembers', 'far_key'=>'dlid', 'foreign_key'=>'uid')
);
}
class Model_List extends ORM
{
protected $_has_many = array(
'contacts'=>array('model'=>'Contact', 'through'=>'listmembers', 'far_key'=>'uid', 'foreign_key'=>'dlid')
);
}
I have to update contact and list relationship in listmemebers table
- create new relationship between existing contact and existing list
- Remove relationship between contact and list
How can I achieve this in Kohana ORM? I can always create model for listmembers and directly add/delete on this model. But is there a way to handle via relationship without creating listmembers model?
I think the documentation explains it quite well: http://kohanaframework.org/3.2/guide/orm/relationships#hasmany-through

Best way to add a second parameter to route

I want my route to be something like cars(/:country/):car_id, what is the best way to do that? Only "cars" will list all the cars and "cars /: country" will list all the cars that are made in that country.
Now I have my route like this resources: cars,: path => "cars (/:country)" and I check in cars#index action if params[:country] is nil to determine what will be retrieved from the database .
My solution feels wrong and ugly and I guess the best solution and cleanest would be to make a country model, but do not really know how to organize it all up, tips?
country must have a slug and so do car_id too (using friendly_id for car_id). It feels like I should have a car table with name and slug thats all i have figured out.
Thanks!
First I'd say that your current solution is NOT ugly, nor wrong, at worst it's pedestrian. But without seeing all the involved models and associations, I can only give a general answer.
First, A country model, probably a good idea, but how do you relate it to the cars model?
You could do this:
class Country << ActiveRecord::Base
has_may :cars
end
class Car << ActiveRecord::Base
belongs_to :country
end
That would support semantics where by you could select a country, and get all cars belonging to a certain country, i.e.
#cars = Country.find('USA').cars
OR, you could do something like:
class Car << ActiveRecord::Base
has_one :country
end
class Country << ActiveRecord::Base
end
That would enable a different semantic:
#country = Car.find('Jeep').country
The point is to think of the query semantics you'd like to have in your app, and then define your associations to support the semantics that make sense for your app. I've posted very simple associations, you may end up with multiple and more complex associations, just depends on how you need to query the database and the associated models.
UPDATE
You posted:
I want my route to be something like cars(/:country/):car_id,
That doesn't make sense, if you know the specific car_id, you don't need any filtering or extra searching.
Sound like you want these URLs:
/cars # all cars
/cars/:country # all cars in country
/car/:id # a specific car
The first and third routes are probably there assuming you've defined the full set of RESTful routes for cars, i.e.
config/routes.rb
resources :cars
You just need to add to routes.rb:
GET '/cars/:country' => 'cars#index'
Then in app/controllers/cars_controller.rb:
def index
if params[:country]
#cars = Car.where("country_id = ?", params[:country])
else
#cars = Car.all
end
end
This assumes you have a relationship set up whereby each car record has a country_id attribute. That can come about in several ways, for example:
class Car < ActiveRecord::Base
belongs_to :country
end
That says my car table has a country_id attribute, and I can do something like:
#car = Car.find(1001)
"The car is in #{#car.country.name}"

Querying through associations with Ruby on Rails

I have a question about doing a query through a few associations using Ruby on Rails.
This question involves querying across three models. (Event, Fight, Fighters). The important parts of the models are as follows:
An event has multiple fights.
Each fight has two fighters: fighter1 and fighter2.
What I need to write is a function to retrieve a list of all fights that have a given fighter. However, this needs to be done through the Event model due to some weird localization thing we have running.
Is there an easy way to do this?
Assuming
class Event
has_many :fights
end
class Fight
has_many :fighters
end
Then you can do:
events = Event.joins(:fights => :fighters).where("fighters.name = 'sally'")
fights = events.inject([]){|a,e| a = a + e.fights; a }