how to work with foreign key field in django - python-3.x

Hi Everyone i am working work django framework, where i used to upload excel file in Dailytrip table, current i get car_mumber from car table, but now i need to store car_number from Car_team table also team_id, i am storing car_id and team_id in car_team table also i need to store team_id in dailytrip table automaticlly based on car_id(car_number) i am to much confuse how to i work that, pls help me out
models.py
class Car_team(BaseModel):
team = models.ForeignKey(
Team,
models.CASCADE,
verbose_name='Team',
null=True,
)
car=models.ForeignKey(
Car,
models.CASCADE,
verbose_name='Car',
null=True)
city =models.ForeignKey(
City,
models.CASCADE,
verbose_name='City',
)
start_date=models.DateField(null=True, blank=True)
end_date=models.DateField(null=True, blank=True)
views.py
def add_payout_uber_daily_data(request):
if request.method == 'POST':
form = UberPerformanceDataForm(request.POST, request.FILES, request=request)
if form.is_valid():
date = form.cleaned_data['date']
excel_file = request.FILES['file']
df = pd.read_excel(excel_file)
is_na = pd.isna(df['Date']).sum().sum() + pd.isna(df['Name']).sum().sum() + pd.isna(df['UUID']).sum().sum() + pd.isna(df['Net Fare With Toll']).sum().sum() + pd.isna(df['Trips']).sum().sum() + pd.isna(df['Uber KMs']).sum().sum() + pd.isna(df['CashCollected']).sum().sum() + pd.isna(df['UberToll']).sum().sum() + pd.isna(df['Tips']).sum().sum() + pd.isna(df['Hours Online']).sum().sum() + pd.isna(df['Ratings']).sum().sum() + pd.isna(df['Acceptance Rate']).sum().sum() + pd.isna(df['Cancellation Rate']).sum().sum()
error_list = []
if is_na > 0:
error_list.append('Found #N/A or blank values in the sheet. Please correct and re-upload')
context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, }
return render(request, 'add_payout_uber_daily_data.html', context=context)
date_match = True
for d in df['Date']:
if str(d.strftime("%Y-%m-%d")) != str(date):
date_match = False
break
if not date_match:
error_list.append('Some dates are not matching in excel')
if len(error_list) > 0:
context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, }
return render(request, 'add_payout_uber_daily_data.html', context=context)
DailyTrip.objects.filter(date=date).update(is_active=0)
for i in df.index:
uuid = df['UUID'][i]
driver_id = None
car_id = None
fleet_id = None
manager_id = None
try:
driver = Driver.objects.get(uber_uuid=uuid)
driver_id = driver.id
except Driver.DoesNotExist:
driver_id = None
#replce car code and store car_number,car_id,team_id via car_team only this logic need to change current get car_number direct car table but we need car_number vai foriegn key
try:
car = Car.objects.get(car_number=df["Car Number"][i])
car_id = car.id
manager_id = car.manager_id
except Car.DoesNotExist:
car_id = None
try:
fleet = Fleet.objects.get(name=df["Fleet Name"][i])
fleet_id = fleet.id
except Fleet.DoesNotExist:
fleet_id = None
name = df['Name'][i]
car_number = df['Car Number'][i]
fare_total = df['Net Fare With Toll'][i]
trips = df['Trips'][i]
pool_trips = 0
hours_online = df['Hours Online'][i]
total_km = df['Uber KMs'][i]
cash_collected = abs(df['CashCollected'][i])
toll = df['UberToll'][i]
tip_amount = df['Tips'][i]
fare_avg = float(fare_total)/int(trips)
fare_per_hour_online = float(fare_total)/float(hours_online)
fare_per_km = fare_total/total_km
trips_per_hour = trips/hours_online
km_per_trip = total_km/trips
rating = df['Ratings'][i]
acceptance_rate_perc = float(df['Acceptance Rate'][i])/100
driver_cancellation_rate = float(df['Cancellation Rate'][i])/100
obj, created = DailyTrip.all_objects.update_or_create(
date=date, uuid=uuid,
defaults={
'car_id': car_id,
'manager_id': manager_id,
'car_number': car_number,
'driver_id': driver_id,
'car_id': car_id,
'fleet_id': fleet_id,
'driver_name': name,
'fare_total': fare_total,
'trips': trips,
'pool_trips': pool_trips,
'hours_online': hours_online,
'total_km': total_km,
'cash_collected': cash_collected,
'toll': toll,
'tip_amount': tip_amount,
'fare_avg': fare_avg,
'fare_per_hour_online':fare_per_hour_online,
'fare_per_km':fare_per_km,
'trips_per_hour': trips_per_hour,
'km_per_trip': km_per_trip,
'rating': rating,
'acceptance_rate_perc': acceptance_rate_perc,
'driver_cancellation_rate': driver_cancellation_rate,
'is_active': 1,
'comments': None}
)
if len(error_list) > 0:
DailyTrip.objects.filter(date=date).update(is_active=0)
context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, }
return render(request, 'add_payout_uber_daily_data.html', context=context)
else:
messages.success(request, 'Daily Trips added Successfully...')
return redirect('/fleet/payout/daily_data/add/uber')
else:
form = UberPerformanceDataForm(initial={})
context = {
'menu_payout': 'active',
'submenu_daily_data': 'active',
'form': form,
}
return render(request, 'add_payout_uber_daily_data.html', context=context)

You can try that :
to get car_number from car_team -->
car_team = car_team.objects.objects.all().last() # to get the last car_team for example
car_number = car_team.car.car_number # to get the car number from the car_team

try:
car = Car.objects.get(car_number=df["Car Number"][i])
car_id = car.id
car1=Car_team.objects.filter(car_id=car_id)
if car1:
team_id=car1[0].team_id
else:
team_id=None
except Car.DoesNotExist:
car_id = None
team_id= None

Related

How to extract the string or name of all foreign keys used in a model in django-pandas dataframe

I have data stored in a Django Model/Table which I am fetching in pandas dataframe via django-pandas (Version: 0.6.6)
The model has 3 columns as foreign key viz: state_name, district_name and block_name
The model.py is as:
####################################################################################
BOOL_CHOICES = ((True, 'Yes'), (False, 'No'))
UNIT_CATEGORIES = (('AMFU', 'AMFU'), ('DAMU', 'DAMU'))
class GroupDetail(models.Model):
"""Village level Whatsapp Information options"""
unit_type = models.CharField(max_length=16, choices=UNIT_CATEGORIES, default="DAMU")
state_name = models.ForeignKey(State, to_field='state_name', on_delete=models.SET_NULL, null=True)
unit_name = models.CharField(max_length=100, default="KVK")
district_name = models.ForeignKey(District, to_field='district_name', on_delete=models.SET_NULL, null=True)
block_name = models.ForeignKey(Block, to_field='block_name', on_delete=models.SET_NULL, null=True)
village_name = models.CharField(max_length=150)
village_covered_through_whatsapp_group = models.BooleanField(verbose_name=_('Village Covered through Whatsapp Group "yes/no"'), choices=BOOL_CHOICES)
number_of_whatsapp_group_created = models.PositiveIntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)])
number_of_farmers_covered_in_the_village = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000)])
objects = DataFrameManager()
class Meta:
db_table = 'Group_Info_Table'
constraints = [models.UniqueConstraint(fields=["state_name","district_name", "block_name", "village_name"], name="all_keys_unique_together")]
def __str__(self):
return self.unit_type
return self.state_name
return self.unit_name
return self.district_name
return self.block_name
return self.village_name
return self.village_covered_through_whatsapp_group
return self.number_of_whatsapp_group_created
return self.number_of_farmers_covered_in_the_village
views.py is as:
Case 1:
PS: kindly look at string of column name passed : state_name__id
If I am fetching data like this, it returns id's of all columns having foreign keys
def amfu_state_wise(request):
state_name_is = None
district_name_is = None
block_name_is = None
if request.method == "POST":
state_name_is=request.POST.get('state')
district_name_is=request.POST.get('district')
block_name_is=request.POST.get('block')
fetch_whole_database = GroupDetail.objects.all()
all_fields = GroupDetail._meta.get_fields()
print("all_fields",all_fields)
fetch_data_df = fetch_whole_database.to_dataframe(['unit_type', 'state_name__id', 'unit_name', 'district_name__id', 'block_name__id', 'village_name', 'village_covered_through_whatsapp_group', 'number_of_whatsapp_group_created', 'number_of_farmers_covered_in_the_village'], index='id')
print("fetch_data_df", fetch_data_df.state_name__id.head(5))
The output in console is as
all_fields id
31618 11
31619 11
31620 11
31621 11
31622 11
Name: state_name__id, dtype: int64
[15/Jun/2022 12:37:36] "GET /damuwhatsapp/amfu_state_wise HTTP/1.1" 200 16811
Case 2:
But when I filter all object of model, it returens NaN value
PS: kindly look at string of column name passed : state_name__name
def amfu_state_wise(request):
state_name_is = None
district_name_is = None
block_name_is = None
if request.method == "POST":
state_name_is=request.POST.get('state')
district_name_is=request.POST.get('district')
block_name_is=request.POST.get('block')
fetch_whole_database = GroupDetail.objects.filter().values().all()
all_fields = GroupDetail._meta.get_fields()
print("all_fields",all_fields)
fetch_data_df = fetch_whole_database.to_dataframe(['unit_type', 'state_name__name', 'unit_name', 'district_name__id', 'block_name__id', 'village_name', 'village_covered_through_whatsapp_group', 'number_of_whatsapp_group_created', 'number_of_farmers_covered_in_the_village'], index='id')
print("fetch_data_df", fetch_data_df.state_name__name.head(5))
The output in console is as
all_fields id
31618 NaN
31619 NaN
31620 NaN
31621 NaN
31622 NaN
Name: state_name__name, dtype: float64
[15/Jun/2022 12:44:24] "GET /damuwhatsapp/amfu_state_wise HTTP/1.1" 200 16811
Case 3:
But when I use
fetch_whole_database = GroupDetail.objects.filter.all()
or
fetch_whole_database = GroupDetail.objects.all()
PS: kindly look at string of column name passed : state_name
def amfu_state_wise(request):
state_name_is = None
district_name_is = None
block_name_is = None
if request.method == "POST":
state_name_is=request.POST.get('state')
district_name_is=request.POST.get('district')
block_name_is=request.POST.get('block')
fetch_whole_database = GroupDetail.objects.filter.all()
all_fields = GroupDetail._meta.get_fields()
print("all_fields",all_fields)
fetch_data_df = fetch_whole_database.to_dataframe(['unit_type', 'state_name', 'unit_name', 'district_name__id', 'block_name__id', 'village_name', 'village_covered_through_whatsapp_group', 'number_of_whatsapp_group_created', 'number_of_farmers_covered_in_the_village'], index='id')
print("fetch_data_df", fetch_data_df.state_name.head(5))
The foreign key string HARYANA is returned with error as :
condition = self.build_lookup(lookups, col, value)
File "/home/webtesting/django_venv/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1273, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/home/webtesting/django_venv/lib/python3.9/site-packages/django/db/models/lookups.py", line 27, in __init__
self.rhs = self.get_prep_lookup()
File "/home/webtesting/django_venv/lib/python3.9/site-packages/django/db/models/lookups.py", line 275, in get_prep_lookup
rhs_value = self.lhs.output_field.get_prep_value(rhs_value)
File "/home/webtesting/django_venv/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 1990, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'HARYANA'.
[15/Jun/2022 13:18:35] "GET /damuwhatsapp/amfu_state_wise HTTP/1.1" 500 159434
So how to get the string of all columns with foreign keys in django-pandas Dataframe?

bad performance for loop with instance and bulk create

I need to use bulk_create to create a lot of "detalle"(details), the problem is i have to iterate trough a json to get the arguments, and i got 4 fk so django ask to me for the instance, not the id. but to have id i have to do a .get(), so i got a bad performance, because its 4 gets by each iteration.
its there a way to get all objects instances and put in a list or something to perform load then the instance without using get every time?
class DetalleFichaAllViewSet(viewsets.ModelViewSet):
serializer_class = DetalleFichaUpdateAllSerializer
def create(self, request, *args, **kwargs):
user = self.request.user
data = request.data
try:
ficha = Ficha.objects.get(autor=user.id)
DetalleFicha.objects.filter(ficha=ficha.id).delete()
except Http404:
pass
# Create Ficha
now = datetime.now()
date_time = now.strftime("%Y-%m-%d %H:%M")
print("AAAAAA DATA:", data)
Ficha.objects.filter(autor=user.id).update(fecha_creacion=date_time, autor=user,
nombre=data["nombreFicha"], descripcion=data["descripcionFicha"])
ficha = Ficha.objects.filter(autor=user.id).last()
recintos = Recinto.objects.all()
productos = Producto.objects.all()
estandar_productos = EstandarProducto.objects.all()
cotizaciones = Cotizacion.objects.all()
detalles_ficha = []
for detalle in data["detalles"]:
recinto = recintos.get(id=detalle[1])
producto = productos.get(id=detalle[10])
estandar_producto = estandar_productos.get(id=detalle[9])
try:
cotizacion = cotizaciones.get(id=detalle[4])
except ObjectDoesNotExist:
cotizacion = None
print("Fecha: ", detalle[8])
detalle = DetalleFicha(carreras=detalle[0],
recinto=recinto, nombre=detalle[2],
cantidad_a_comprar=detalle[3], cotizacion=cotizacion,
valor_unitario=detalle[5], valor_total=detalle[6],
documento=detalle[7], fecha_cotizacion=detalle[8],
estandar_producto=estandar_producto, producto=producto,
ficha=ficha)
detalles_ficha.append(detalle)
DetalleFicha.objects.bulk_create(detalles_ficha)
print("Array convertida", detalles_ficha)
print(detalles_ficha[0])
return Response(status=status.HTTP_200_OK)

Initialize Model Class Variable At Runtime

I am trying to import student data from an Excel workbook. I have to select column_name of the class StudentMasterResource dynamically which is present in the file. I got all column name in constants module has one dictionary which name column_name. When I do it for the first time, it works, then it fails
constants.py
column_name = dict()
resource.py
from common_account import constants
from import_export import widgets, fields, resources
def getClassName(key):
if key in constants.column_name:
return constants.column_name[key]
return key
class StudentMasterResource(resources.ModelResource):
organisation_id = fields.Field(
column_name=getClassName('organisation_id'),
attribute='organisation_id',
widget=widgets.ForeignKeyWidget(OrganisationMaster, 'organisation_name'),
saves_null_values=True
)
name = fields.Field(
column_name=getClassName('Name'),
attribute='name',
saves_null_values=True,
widget=widgets.CharWidget()
)
date_of_birth = fields.Field(
column_name=getClassName('date'),
attribute='date_of_birth',
saves_null_values=True,
widget=widgets.DateWidget()
)
views.py
from common_account import constants
from tablib import Dataset
#api_view(['POST'])
#permission_classes([IsAuthenticated])
def student_import(request):
if request.method == 'POST':
context_data = dict()
data_set = Dataset()
file = request.FILES['myfile']
extension = file.name.split(".")[-1].lower()
column_data = request.data
is_import = column_name['is_import']
constants.valid_data.clear()
constants.invalid_data.clear()
if extension == 'csv':
data = data_set.load(file.read().decode('utf-8'), format=extension)
else:
data = data_set.load(file.read(), format=extension)
constants.column_name = {
'date' : column_data.get('birth'),
'name' : column_data.get('name'),
}
if is_import == 'No':
result = student_resource.import_data(data_set, organisation_id = request.user.organisation_id,
offering_id = offering_id,all_invalid_data = False, dry_run=True, raise_errors=True)
context_data['valid_data'] = constants.valid_data
context_data['invalid_data'] = constants.invalid_data
context_data[constants.RESPONSE_RESULT] = {"Total records":student_resource.total_cnt,
"skip records":len(constants.invalid_data),
"Records imported": len(constants.valid_data),
}
return JsonResponse(context_data)
elif is_import == 'Yes':
result = student_resource.import_data(data_set, organisation_id = request.user.organisation_id,
offering_id = offering_id,all_invalid_data = False, dry_run=False, raise_errors=False)
context_data[constants.RESPONSE_ERROR] = False
context_data[constants.RESPONSE_MESSAGE] = 'Data Imported !!!'
context_data[constants.RESPONSE_RESULT] = {"Total records":student_resource.total_cnt,
"skip records":len(constants.invalid_data),
"Records imported": len(constants.valid_data),
}
return JsonResponse(context_data)

Save method of Django model does not update fields of existing record even if force update

I am trying to update the record that already exists in the database and therefore I use this code
if 'supplierId' not in req.keys():
return JsonResponse({'code': 0, 'msg': "supplier was not selected", 'result': ''}, safe=False)
assigneeId = User.objects.get(pk=req.get('assigneeId', 1))
responsibleId = User.objects.get(pk=req.get('responsibleId', 1))
redistributionMethod = req.get('redistributionMethod', 0)
amount = req.get('allCost', 0)
procurement_doc = ProcurementDocJournal.objects.get(id=pk)
print(procurement_doc)
procurement_doc.docType = req['docType']
procurement_doc.status = req['status']
procurement_doc.companyId = Company.objects.get(pk=req['companyId'])
procurement_doc.datetime = req['datetime']
procurement_doc.supplierId = Partner.objects.get(pk=req['supplierId'])
procurement_doc.assigneeId = assigneeId
procurement_doc.warehouseId = Warehouse.objects.get(pk=req['warehouseId'])
procurement_doc.responsibleId = responsibleId
procurement_doc.redistributionMethod = redistributionMethod
procurement_doc.amount = amount
procurement_doc.comment = req['comment']
procurement_doc.save(force_update=True, update_fields=['comment', 'amount', 'redistributionMethod',
'responsibleId', 'warehouseId',
'supplierId', 'datetime',
'companyId', 'assigneeId', 'status', 'docType'])
where req contains a request
something like this
{
'docType': 3,
'status': 1,
'companyId': '2',
'warehouseId': '3',
'assigneeId': '5',
'supplierId': '12671',
'responsibleId': '5',
'datetime': '2020-04-01 08:01:00',
'comment': ''
}
As you can see there is a print which assures me that I selected the correct row
when I noticed that these records are not updated I searched for causes and found
this question where the guy who asked says The message field was missing from the model definition
in my case, none of these are missing from the model's description
class ProcurementDocJournal(models.Model):
id = models.IntegerField(primary_key=True, null=False)
docNumber = models.IntegerField()
status = models.IntegerField()
docType = models.IntegerField()
depended = models.IntegerField()
companyId = models.ForeignKey(Company, on_delete=models.CASCADE,
db_column='companyId')
created_at = models.DateTimeField(auto_now_add=True)
datetime = models.DateTimeField()
currencyId = models.ForeignKey(Currency, db_column='currencyId', on_delete=models.CASCADE)
currencyRate = models.FloatField()
redistributionMethod = models.IntegerField()
assigneeId = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ProcurementDocJournal',
db_column='assigneeId')
warehouseId = models.ForeignKey(Warehouse, on_delete=models.CASCADE,
db_column='warehouseId')
responsibleId = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ProcurementDoc',
db_column='responsibleId')
supplierId = models.ForeignKey(Partner, on_delete=models.CASCADE,
db_column='supplierId')
amount = models.FloatField()
comment = models.TextField()
class Meta:
db_table = 'procurementDocJournal'
get_latest_by = 'id'
Edit
I have an action that contains
procurement_doc_journal_item = ProcurementDocJournal.objects.get(id=pk)
currencyId = req['currency']
currency = Currency.objects.get(id=currencyId)
currencyRate = CurrencyRate(date, currency.name)
procurement_doc_journal_item.currencyId = currency
procurement_doc_journal_item.currencyRate = currencyRate['rate']
procurement_doc_journal_item.save()
and works like a charm
there is no any error that logs say
You don't specify if there's any error in your logs. I'd kind of expect to see something since if it's not saving, it must be bombing out before that as no fields are mandatory.
I am, however, not sure you're setting your FKs correctly here:
procurement_doc.companyId = Company(req['companyId'])
Should be
procurement_doc.companyId = Company.objects.get(pk=req['companyId'])
and that assumes companyId is set to a value that exists of course ... Whether this is the source of your issue or not, I'm not sure. I don't see any of your FKs are mandatory.
Edit: I've just tested this on one of my models with a simple id key:
>>> Contact(1)
Contact()
>>> c = Contact(1)
>>> c.name
''
>>> c = Contact.objects.get(pk=1)
>>> c.name
'Mike'
It really doesn't seem to me as though it works ...
Sidenote: You can simplify code like this:
if 'allCost' not in req.keys():
amount = 0
else:
amount = req['allCost']
By doing:
amount = req.get('allCost', 0)

how can I make an insert of a select field with sqlalchemy?

I have a form where I have a text field and a selection field and the question I have is how can I insert the bd in the selection field, this field in the table is an external key and what I need is to insert the value of the selection field.
I would greatly appreciate your help.
#detalle_grupo_estadisticas.route("/show/<id>", methods = ['GET', 'POST'])
def show(id):
title = 'Grupo estadisticas'
page = 1
per_page = 3
CamposGrupo = forms.Fields_Detalle_Grupo_Estadisticas(request.form)
grup_list = GrupoEstadisticas.query.all()
if request.method == 'POST' and CamposGrupo.validate():
grupo_edit = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
grupo_edit.nombre = CamposGrupo.Nombre.Data
grupo_edit.id_grupoEstadisticas = CamposGrupo.GrupoEstadistica.Value
db.session.add(grupo_edit)
db.session.commit()
return redirect(url_for('detalle_grupo_estadisticas.index'))
grupo = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
CamposGrupo.Nombre.data = grupo.nombre
CamposGrupo.GrupoEstadistica.choices=[(g.id_grupoEstadisticas,g.nombre) for g in grup_list]
return render_template('/detalle_grupo_estadisticas/show.html', title=title, CamposGrupo = CamposGrupo, grupo = grupo)
What I want to insert is the value of the field selection field
these are the models
class DetalleGrupoEstadisticas(db.Model):
__tablename__ = 'detalle_grupo_estadisticas'
id_detalle_grupo_estadisticas = db.Column(db.Integer, primary_key=True)
nombre = db.Column(db.String(80), nullable=False)
id_grupoEstadisticas = db.Column(db.Integer, db.ForeignKey('grupo_estadisticas.id_grupoEstadisticas'))
grupoestadistica = db.relationship('GrupoEstadisticas', back_populates='detallesgrupo', lazy=True)
class GrupoEstadisticas(db.Model):
__tablename__ = 'grupo_estadisticas'
id_grupoEstadisticas = db.Column(db.Integer, primary_key=True)
nombre = db.Column(db.String(80), nullable=False)
descripcion = db.Column(db.String(200), nullable=False)
estadisticas= db.relationship('Estadisticas', back_populates='grupoestadisticas', lazy=True)
detallesgrupo= db.relationship('DetalleGrupoEstadisticas', back_populates='grupoestadistica', lazy=True)
This is how I was able to solve the problem.
view
#detalle_grupo_estadisticas.route("/show/<id>", methods = ['GET', 'POST'])
def show(id):
title = 'Grupo estadisticas'
page = 1
per_page = 3
CamposGrupo = forms.Fields_Detalle_Grupo_Estadisticas(request.form)
grup_list = GrupoEstadisticas.query.all()
if request.method == 'POST' and CamposGrupo.validate():
grupo_edit = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
grupo_edit.nombre = CamposGrupo.Nombre.data
grupo_edit.grupoestadistica = CamposGrupo.GrupoEstadistica.data
#this is where I had the error that I was inserting in id_grupoStadisticas and it had to be with the variable of the relationship
db.session.add(grupo_edit)
db.session.commit()
return redirect(url_for('detalle_grupo_estadisticas.index'))
grupo = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
CamposGrupo.Nombre.data = grupo.nombre
CamposGrupo.GrupoEstadistica.choices=[(g.id_grupoEstadisticas,g.nombre) for g in grup_list]
return render_template('/detalle_grupo_estadisticas/show.html', title=title, CamposGrupo = CamposGrupo, grupo = grupo)
form
class Fields_Detalle_Grupo_Estadisticas(Form):
Nombre = StringField('Grupo', validators=[InputRequired(), Length(min=2, max=30, message = 'Mayor a 2 caracteres y menor a 30')])
GrupoEstadistica = QuerySelectField('Grupo Estadistica',query_factory=lambda: GrupoEstadisticas.query,
get_pk=lambda g: g.id_grupoEstadisticas,
get_label=lambda g: g.nombre)

Resources