I define a table with flask-sqlalchemy. A special field start with a number, as below:
class Foo(db.Model):
6F78 = db.Column(db.String(10))
The field name 6F78 causes SyntaxError: invalid syntax.But the field name can't modify to another name, as it is constant.
So, what should I do? Thanks!
Python identifiers can't start with a number, which is why you can't create a member on an object name 6F78.
You can however point your representation of that column in your code to a column in the database of a different label, try this:
class Foo(db.Model):
my_column_name_6F78 = db.Column( "6F78", db.String() )
Then in code you refer to my_column_name_6F78 instead of 6F78. If course you could chose a more concise name for the column in your code, like c6F78.
Related
I am experimenting with graphene in setting
1.) A default value for a field (just like how defaultdict works in python)
Ex :-
Class something(graphene.ObjectType):
FieldA = graphene.Float() or return a defaultValue
2.) Set a field of multiple type
Ex:-
Class something(graphene.ObjectType):
FieldA = graphene.Float() or graphene.String() or None
I am new to graphene & I am going through the documentation.
Any help/pointer is appreciated in getting the above 2 done.
1. For default values...
The docs don't do a great job of showing examples but the info you need is here: https://docs.graphene-python.org/en/latest/types/scalars/
All Scalar types accept the following arguments. All are optional:
name: string
Override the name of the Field.
description: string
A description of the type to show in the GraphiQL browser.
required: boolean
If True, the server will enforce a value for this field. See NonNull.
Default is False.
deprecation_reason: string
Provide a deprecation reason for the Field.
default_value: any
Provide a default value for the Field.
i.e. you can do:
class Something(graphene.ObjectType):
field_a = graphene.Float(default_value=1.23)
(note the capitalization: class keyword must be lowercase in Python, while Something class name, by convention, should be "camel case" i.e. first letter of each word capitalized, also by convention the field_a attribute should be "snake case" i.e. all lower-case with underscores as word separator)
2. For field of multiple types...
The info you need is here: https://docs.graphene-python.org/en/latest/types/unions/
i.e. you can do:
class StringOrFloat(graphene.Union):
class Meta:
types = (graphene.String, graphene.Float)
class Something(graphene.ObjectType):
field_a = StringOrFloat()
I need to retrieve a value from a Many-To-Many query. Let's say I have 3 models: Toy, Part, and ToyParts
ToyParts has a field called "part_no". I need to be able to get the value of this.
class Toy(models.Model):
parts = models.ManyToManyField(Part, through="ToyParts")
class Part(models.Model):
pass
class ToyParts(models.Model):
toy = models.ForeignKey(Toy, ...)
part = models.ForeignKey(Part, ...)
part_no = models.CharField(...)
I've tried using:
toy.parts.all().first().part_no
which obviously doesn't work as Part does not have a field called "part_no"
I've also tried just simply using:
ToyParts.objects.filter(toy=..., part=...)
but that adds additional queries.
How would I be able to get part_no without querying ToyParts directly?
I've tried using: toy.parts.all().first().part_no
The part_no field is declared on the model ToyParts. You therefore need to get an instance of ToyParts to access this field. Assuming you have a Toy instance you can use the reverse relation to ToyParts, which defaults to toyparts_set, as follows:
toy.toyparts_set.first().part_no
How would I be able to get part_no without querying ToyParts directly?
You can't. If you want to reduce the number of queries you can use select_related:
for tp in toy.toyparts_set.select_related('part').all():
print(tp.part_no, tp.part.id)
In this example tp.part doesn't require an extra query as the part instance is already fetched by select_related.
I am during creating my first database project in SQLAlchemy and SQLite. I want to connect two entity as relational database's relational model. Here is the source:
class Models(Base):
__tablename__ = "models"
id_model = Column(Integer, primary_key=True)
name_of_model = Column(String, nullable = False)
price = Column(Integer, nullable = False)
def __init__(self, name_of_model):
self.name_of_model = name_of_model
class Cars(Base):
__tablename__ = "cars"
id_car = Column(Integer, primary_key=True)
id_equipment = Column(Integer, nullable = False)
id_package = Column(Integer, nullable = False)
id_model = Column(Integer, ForeignKey('Models'))
model = relationship("Models", backref=backref('cars', order_by = id_model))
I want to achieve a relationship like this:
https://imgur.com/af62zli
The error which occurs is:
The foreign key associated with column 'cars.id_model' could not find table 'Models' with which to generate a foreign key to target column 'None'.
Any ideas how to solve this problem?
From the docs:
The argument to ForeignKey is most commonly a string of the form
<tablename>.<columnname>, or for a table in a remote schema or “owner”
of the form <schemaname>.<tablename>.<columnname>. It may also be an
actual Column object...
In defining your ForeignKey on Cars.id_model you pass the string form of a class name ('Models') which is not an accepted form.
However, you can successfully define your foreign key using one of the below options:
ForeignKey(Models.id_model)
This uses the actual Column object to specify the foreign key. The disadvantage of this method is that you need to have the column in your namespace adding extra complexity in needing to import the model into a module if it is not defined there, and also may cause you to care about the order of instantiation of your models. This is why it's more common to use one of the string-based options, such as:
ForeignKey('models.id_model')
Notice that this example doesn't include the string version of the class name (not Models.id_model) but rather the string version of the table name. The string version means that table objects required are only resolved when needed and as such avoid the complexities of dealing with Column objects themselves.
Another interesting example that works in this case:
ForeignKey('models')
If the two columns are named the same on both tables, SQLAlchemy seems to infer the column from the table. If you alter the name of either of the id_model columns definitions in your example so that they are named differently, this will cease to work. Also I haven't found this to be well documented and it is less explicit, so not sure if really worth using and am really just mentioning for completeness and because I found it interesting. A comment in the source code of ForeignKey._column_tokens() seemed to be more explicit than the docs with respect to acceptable formatting of the column arg:
# A FK between column 'bar' and table 'foo' can be
# specified as 'foo', 'foo.bar', 'dbo.foo.bar',
# 'otherdb.dbo.foo.bar'. Once we have the column name and
# the table name, treat everything else as the schema
# name.
If I have a web app that use only one language and it is not English, is that correct to use model field verbose_name attribute for the field description (that will be printed in form)? I dont use the translation modules.
Verbose Field Names are optional. They are used if you want to make your model attribute more readable, there is no need to define verbose name if your field attribute is easily understandable. If not defined, django automatically creates it using field's attribute name.
Ex : student_name = models.CharField(max_length=30)
In this example, it is understood that we are going to store Student's name, so no need to define verbose explicitly.
Ex : name = models.CharField(max_length=30)
In this example, one may be confused what to store - name of student or Teacher. So, we can define a verbose name.
name = models.CharField("student name",max_length=30)
I'm defining a sqlalchemy model like this:
class Dog(Model):
__tablename__ = 'dog'
id = db.Column(db.Integer, primary_key=True)
owner = db.Column(db.Integer, db.ForeignKey('owner.id'))
I want to use the inspector to figure out a type for each attribute, however I'm having trouble figuring out how to access the things I want, which include (a) a type for each attribute and (b) all of the other properties that I've passed into Column.
I tried the following:
for column in inspect(target_class).columns:
print column.type
This returns:
INTEGER
INTEGER
but really I'd like something like
INTEGER
FOREIGN_KEY
or at least some way to recognize that I'm using the second Integer to identify another table.
What is the most correct way to do this? If possible, I'm also interested in grabbing all of the kwargs that I passed into db.Column.
You can look at the foreign_keys property on Column:
for column in inspect(Dog).columns:
print column.foreign_keys
# set([])
# set([ForeignKey('owner.id')]
There are other properties set from kwargs, like primary_key:
for column in inspect(Dog).columns:
print column.primary_key
# True
# False