SqlAlchemy db.metadata.create_all - does not create table when __bind_key__ has been specified? - sqlalchemy

When I create a class (Table), and I specify the bind_key = "bindingname" the table is not created using this method:
db.metadata.create_all(db.engines["bindingname"])
however, when I remove the bind_key property from the table class, the table is indeed created, however it will get created in all my bindings ...
how can i specify bind_key in a class table definition and then ensure that the table is created only in the specified database?

Aha, managed to get it working like this.
Example of class
from models.Models import db
class V3_Output_Binned(db.Model):
__bind_key__ = "output_v3"
__tablename__ = "V3_Output_Bin"
Example of how and where to create the missing tables, I need to do this since there is one database (binding) that I do not want to have table schemas auto created.
db.init_app(app)
#app.before_first_request
def create_table():
#db.create_all()
with app.app_context():
db.create_all(bind_key="default")
db.create_all(bind_key="output")
db.create_all(bind_key="output_v3")
If you need more information - having the same issue, let me know and I will give advice.

Related

django migrate primary OneToOneFiled ForeignKey + into composite foreign key

I've a model which is just a relation between two entities like this:
class SomeModel(models.Model):
a = OneToOneField(User,primary_key=True,...)
b = ForeignKey(Car,...)
As per design, it was correct, as I didn't want an User to have multiple Car. But in my new design, I want to accept multiple Car to an User. So I was trying something like this:
class SomeModel(models.Model):
class Meta:
unique_together = (("a", "b"),)
a = ForeignKey(User,...)
b = ForeignKey(Car,...)
But during migration, it asks me:
You are trying to add a non-nullable field 'id' to somenmodel without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
I just wanted to remove that foreign key from OneToOneRelation and add a new id combining both. - How to resolve this?
Delete the model and table from the database and create a new model from starting or add null=True to the given field. you must be having some data (rows) in your table and now you are creating a new column, so previous rows need something to be there in the newly created column, writing null = True will do that.

Is it possible to include a ForeignKey inside a JSONField schema? How else can I effect this?

I am building an app in Django that allows users to build their own forms and in effect customise dynamic models.
After much research, I've decided to effect this through Django, PostgreSQL and JSONFields where one model holds the schema and another holds the record data:
class = Template(models.Model):
schema = JSONField(null=True) # Schema for the form/model
class = DynamicModel(models.Model):
data = JSONField(null=True) # Corresponding data for the form/model
template = models.ForeignKey(Template, null=True,
blank=False, on_delete=models.SET_NULL)
This means users can define their own model templates and I can hold different records using that template in another model.
The idea is to parse the template.schema JSONField to display editable forms using jQuery and to store the output as dynamicmodel.data JSONField. Validations are passed on the client side.
However, this comes with the drawback if I want to allow users to include ForeignKey lookups in their models. For example, say they wanted to add a choice box that offered selections from different customer.ids in a Customer(models.Model) class.
Without hardcoding the ForeignKey directly into the DynamicModel class (which would defeat the point of the exercise) can you think of a way I can achieve this?

Order of defining association object, related tables using Flask-SQLAlchemy?

I'm working through Miguel Grinberg's Flask book.
In chapter 12, he has you define an association object Follow with followers and the followed, both mapping to a user, as well as adding followers and followed to the Users class.
I originally put the association table after the User table, and got an error when I ran python manage.py db upgrade:
line 75, in User followed = db.relationship('Follow', foreign_keys= [Follow.follower_id],
NameError: name 'Follow' is not defined
Then I moved the association object class Follow above the class User definition, and re-ran the migration. This time it worked.
Can someone explain the reason for this?
Both class definitions seem to need the other.
Is order something I should know about flask-sqlalchemy specifically, sqlalchemy, or ORM in general?
The SQLAlchemy documentation says "we can define the association_table at a later point, as long as it’s available to the callable after all module initialization is complete" and the relationship is defined in the class itself.
That is, for the case you're using and association_table to show the relationship between two separate models. I didn't see anything about this case in the Flask-SQLAlchemy or SQLAlchemy documentation, but it's very possible I just didn't recognize the answer when I saw it.
class User(UserMixin, db.Model):
__tablename__ = 'users'
...
followed = db.relationship('Follow',
foreign_keys=[Follow.follower_id],
backref=db.backref('follower', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')
followers = db.relationship('Follow',
foreign_keys=[Follow.followed_id],
backref=db.backref('followed', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')
Order of definition with:
class Follow(db.Model):
__tablename__ = 'follows'
follower_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
followed_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
Or maybe order doesn't matter at all, and I am misattributing a problem?
First of all if you are going to use some class in later it must be defined already. The defination order is important, you can not use a class which doesn't exist yet.
Second, sqlalchemy says you will defined a third table to create relationship. If you use this approach User and Follow class would not access each other attributes so it won't cause defination order error.
Finally, if you won't define an associate table then you have to put classes in right order, to use attributes of them.

Sequelize (v1.5) and node

How can I check whether a field exists in my table, via sequelize orm.
Note that I have already defined the full object model. I just need to check whether a particular field exists or not.
You can see what is inside your database via:
sequelize.getQueryInterface().describeTable('nameOfTableHere').success(function(data){})
If you want to check the table of a specific model you could also do this:
sequelize.getQueryInterface().describeTable(Model.tableName).success(function(data) {})
Since I had already defined the object model, the following expression gives an array of field names defined in the model.
Object.keys(Model.rawAttributes)

Create Active/Archive Models in a DRY way (Django)

I have a model like the following, which is growing too large and needs to be split into a separate active table. At the end of the day, one table will contain all objects and the other will only contain active objects.
class Tickets(models.Model):
price = ....
number = .....
date = ....
active = ....
parent = models.ForeignKey('self', related_name='children')
ManyMoreFields
There are two sources of complexity:
1) The parent field on the ActiveTickets table is going to point to the Tickets table. The related_name should not change.
2) The ActiveTickets and Tickets table both have proxy Models that inherit from them.
class CityTickets(Tickets):
class Meta:
proxy = True
class ActiveCityTickets(ActiveTickets):
class Meta:
proxy = True
Obviously, I could just copy and paste all of the fields in Ticket (there are many), but that is not the right way of doing it. I've tried to use Abstract inheritance and Mixins (defining the fields in a separate class that is inherited by both Tickets and ActiveTickets).
One issue with abstract inheritance is that the ForeignKey field, parent, is causing issues since it's duplicative and the related_name is the same. Generally, my attempts have caused my unit and functional tests to fail.
What are some elegant approaches here? Should I think about creating two separate MySQL tables and then just using a single Model with multiple managers (and db routers)? Is that reasonable?
Maybe this helps:
class Base(models.Model):
m2m = models.ManyToManyField(OtherModel, related_name="%(app_label)s_%(class)s_related")
class Meta:
abstract = True
https://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name