How to set a default value for a field in graphene - python

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()

Related

Create pydantic model for Optional field with alias

Pydantic model for compulsory field with alias is created as follows
class MedicalFolderUpdate(RWModel):
id : str = Field(alias='_id')
university : Optional[str]
How to add optional field university's alias name 'school' as like of id?
It is not documented on the Pydantic website how to use the typing Optional with the Fields Default besides their allowed types in which they include the mentioned Optional:
Optional[x] is simply shorthand for Union[x, None]; see Unions below for more detail on parsing and validation and Required Fields for details about required fields that can receive None as a value.
for that, you would have to use their field customizations as in the example:
class Figure(BaseModel):
name: str = Field(alias='Name')
edges: str = Field(default=None, alias='Edges')
without the default value, it breaks because the optional does not override that the field is required and needs a default value. Which is the solution I used to overcome this problem while using Pydantic with fast API to manage mongo resources

How to set default values into an Array Field Django?

I would like to know how to set default values into a Django Array Field Model.
I have a TextChoices model named "GameType" :
class GameType(models.TextChoices):
'''
Enumeration of all different game types
'''
EVIL = 'evil', 'evil'
SOLOCOOP = 'solo', 'solo'
MULTI = 'multi', 'multi'
And in my Item model, I can choose in each mode my item is available. Then I have these lines :
game_types = ArrayField(
models.CharField(
default=GameType.SOLOCOOP,
max_length=40,
choices=GameType.choices
), default=default_item_game_types, null=False, blank=False)
Two things :
The first default key "GameType.SOLOCOOP" doesn't work
The default list doesn't work too
Here is my "default_item_game_types" function :
def default_item_game_types():
'''Default callable to avoid errors
'''
return list(GameType)
And in my CMS, I don't have my default values :
Screenshot of my Game types field
I tried many things and searched many solutions but nothing matched in my case.
Is there any response to fix my issues ?
Thanks for your time
Regards,
Steven
1: You need to set it like
self.SOLOCOOP = 'solo'
Can do this in a custom method or init if you know the defaults for it, that would be much easier than calling the custom method.
2:The default values are based on the Charfield as it is an Array of fields in some sense.
EDITED:
Just do the str_value then or better just do the key value for solar as you're already using it as choices in the parameter below.

How to declare a time-based alphanumerical id field with predefined aplphabetic part (Django model)

I am developing an app in Django.
I wanted to insert in my model an auto-incrementing alphanumerical unique ID field, having, by default, a fixed alphabetical part and an auto-incrementing numerical part. But I also want the availability to change, from admin section, this id to another alphanumerical one, with a different alphanumerical and numerical part.
I tryed to implement this, but it turned out that trying to implement such a field and making it the autofield of the model generates problems in my database.
So I am changing my aim: now I want to implement a time-based alphanumerical unique field with predefined aplphabetic part. Please note: I don't want to overwrite the django default id field, I just want to include in my model a field that gets as default value a unique customized alphanumerical value.
Here is what I did, in my models.py:
def return_timestamped_id():
prefix = "ITCH"
import time
this_time = time.time()
this_time = this_time *10000000
this_time = int(this_time)
timestamp = str(this_time)
default_value = prefix + timestamp
return(default_value)
class object_example(models.Model):
name = models.CharField(max_length=256, blank=True, null=True)
Id_generated = models.CharField(max_length=256, blank=False, null=False, unique=True, default=return_timestamped_id())
The problem is that, as I add objects to this model from the admin section, The
Id_generated is always the same.
I expected that the return_timestamped_id() function was called every time I add a new object. It is clear instead that is called just once and then the same return value is passed to the Id_generated of every new object.
How can I change my code in order to get a different timestamp every time a new object is added?
As you probably saw in the Django docs, you can use either a value or a callable as a default. If you use a callable (e.g. a function) then it will be called each time a default is needed.
The problem: you were passing a value because you were calling your function default=return_timestamped_id(). The function was being called once, when your module (models.py) was imported into the application.
The solution: pass the function itself default=return_timestamped_id
You can see in the django.models.Fields class the relevant code (comments mine):
class Field():
def __init__(self, ..., default=NOT_PROVIDED,...):
...
self.default = default # save the default as a member variable
...
def get_default(self):
"""Return the default value for this field."""
return self._get_default()
#cached_property
def _get_default(self):
if self.has_default():
if callable(self.default): # if it is callable, return it
return self.default
return lambda: self.default # else wrap in a callable

How does model class default keyword works in sqlalchemy

I have set mapping for a column in my model class as
class Plan(Base):
__tablename__ = "plans"
`default_c = Column(Boolean, default=False)`
But when i am inserting data to this table using . below code. I am still getting (exceptions.TypeError) Not a boolean value: '' . I have default_c field empty in my dictionary. I was wondering if the default should have handled this.
conn.execute(Plan.__table__.insert(), Plan_dict)
Plan_dict is my list of dictionaries which I want to insert into plans table.
According to documentation if you don't provide the column then it will populate the default value
A scalar, Python callable, or ColumnElement expression representing the default value for this column, which will be invoked upon insert if this column is otherwise not specified in the VALUES clause of the insert. This is a shortcut to using ColumnDefault as a positional argument; see that class for full detail on the structure of the argument.
I feel that you are giving the default_c an empty value. Remove the default_c from your Plan_dict and give it a try.

Optional but not empty field in WTForms

The Optional validator allows for both empty values and if the value is not present (from the docs):
class wtforms.validators.Optional(strip_whitespace=True)
Allows empty input and stops the validation chain from continuing.
If input is empty, also removes prior errors (such as processing
errors) from the field.
I have some additional validators on a field, and I would like if those validators ran even if the input is an empty string. The builtin Optional validator makes the rest of the validators skipped if the input was an empty string. Is there a built in or any other way to achieve this?
Edit: More specifics about my usecase
I am using this form to validate PUT requests. Let's say I have User entities with usernames as ID and middlenames as an optional field. Then the validator for the fields would look something like:
class UserUpdateForm(Form):
username = fields.StringField('username', [
validators.Optional(),
validators.Length(min=5, max=500)
])
middlename = fields.StringField('middlename', [
validators.Optional()
])
So I would allow for PUT requests that does not have a username or middlename parameter, and those would leave the fields untouched. However, when the parameter is present and is an empty string, I would like the username field validation fail because of the Length validator, but I would allow the middlename field to be set to the empty string.
From another perspective: I would like to distinguish non-present parameters and empty string parameters.
I took a look at the source of the Optional validator:
class Optional(object):
...
def __call__(self, form, field):
if not field.raw_data or isinstance(field.raw_data[0], string_types) and not self.string_check(field.raw_data[0]):
field.errors[:] = []
raise StopValidation()
As you can see in and not self.string_check(field.raw_data[0]), empty strings are explicitly considered here. I wonder what would happen if I sent two values like a=foo&a=&b=bar.
Anyway, the quick solution for me was to implement a new validator:
class OptionalButNotEmpty(object):
"""
Allows missing but not empty input and stops the validation chain from continuing.
"""
# Code is a modified version of `Optional` (https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py#L148)
field_flags = ('optional', )
def __call__(self, form, field):
if not field.raw_data:
raise wtforms.validators.StopValidation()

Categories