i'm developing a web app that will guide the student what to choose on his next year , if the general average > 12 and specialite ==Si he can choose Si else he is obliged to choose ISIL
i want to update the specialite into ISIL
PS : im new at django
views.py :
def resultats(request,id=None):
etudiant = MyUser.objects.all
etud_si = MyUser.objects.all().filter(specialite='SI')
etud_isil = MyUser.objects.all().filter(specialite='ISIL')
moy = MyUser.objects.all().annotate(moyenne =(F('moyenne_s1')+F('moyenne_s2'))/2).filter(moyenne__gt=11.99,specialite='SI')
moy1 = MyUser.objects.all().annotate(moyenne =(F('moyenne_s1')+F('moyenne_s2'))/2).filter(moyenne__lt=11.99,specialite='SI')
if moy1 :
moy1.specialite = 'ISIL'
moy1.save()
if id:
pr = get_object_or_404(MyUser,id=id)
else:
pr = request.user
context = {
'etudiant':etudiant,
'profile':pr,
'etud_si':moy,
'etud_isil':moy1
}
return render(request,'resultats.html',context)
models.py :
class MyUser(AbstractBaseUser,PermissionsMixin):
SI = 'SI'
ISIL = 'ISIL'
SPEC_CHOICES = [
(SI,'SI - System Informatique'),
(ISIL,'ISIL - Ingenieur system informatique et logiciels')
]
username = models.CharField(
max_length=300,
validators = [
RegexValidator(regex = USERNAME_REGEX,
message = 'Nom d\'utilisateur doit etre Alphanumeric',
code = 'nom d\'utilisateur invalid'
)],
unique = True
)
email = models.EmailField(unique = True)
nom = models.CharField(default=' ',max_length=300)
prenom = models.CharField(default=' ',max_length=300)
moyenne_s1 =models.DecimalField(default=00.00,max_digits=4,decimal_places=2)
moyenne_s2 = models.DecimalField(default=00.00,max_digits=4,decimal_places=2)
specialite = models.CharField(max_length=300,choices=SPEC_CHOICES,default=SI)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','moyenne_s1','moyenne_s2']
def get_update(self):
return reverse("edit", kwargs={"id": self.id})
#property
def moyenne_gen(self):
return (self.moyenne_s1+self.moyenne_s2)/2
I Solved it :
def resultats(request,id=None):
etudiant = MyUser.objects.all
moy = MyUser.objects.all().annotate(moyenne =(F('moyenne_s1')+F('moyenne_s2'))/2).filter(moyenne__gt=11.99,specialite='SI')
moy1 = MyUser.objects.all().annotate(moyenne =(F('moyenne_s1')+F('moyenne_s2'))/2).filter(moyenne__lt=11.99)
if moy1 :
moy1.specialite = 'ISIL'
moy1.update(specialite='ISIL')
if id:
pr = get_object_or_404(MyUser,id=id)
else:
pr = request.user
context = {
'etudiant':etudiant,
'profile':pr,
'etud_si':moy,
'etud_isil':moy1
}
return render(request,'resultats.html',context)
Related
I would like to know how to modify the way I represent the JSON Response of my requests to the API created with DRF, tabs, spaces, etc..., in order to respond exactly to my frontend app.
I have the following code:
My models.py extract:
class Email(models.Model):
user_email = models.CharField(primary_key=True, max_length=200)
user_phone_number = models.IntegerField()
user_device_id = models.CharField(max_length=200)#request.META.get('HTTP_DEVICE', '')
lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
lng = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
user_address = models.CharField(max_length=200)
creation_date = models.DateTimeField(default=None)
email_status = models.BooleanField(default=False)
email_score = models.IntegerField()
valid_email = models.BooleanField(default=False)
fraud = models.BooleanField(default=False)
My views.py extract:
class UserListView(APIView):
serializer_class = EmailSerializer
queryset = Email.objects.all()
pagination_class = StandardResultsSetPagination
def get_serializer_class(self):
if self.action == 'list':
return EmailListSerializer
return EmailSerializer
def post(self, request, *args, **kwargs):
parametros = request.POST
email='email=' + request._full_data['user_email']
response = UserConnector(email).get_user_data()
obgs = response[1]['results']
if len(obgs) == 0:
user_email = self.request.POST.get('user_email')
email_stat = ''
email_scor = ''
email_valid = ''
frau = ''
else:
obg = response[1]['results'][0]
user_email = self.request.POST.get('user_email')
email_stat = obg.get('email_status')
email_scor = obg.get('email_score')
email_valid = obg.get('valid_email')
frau = obg.get('fraud')
NewEmail = Email(
user_email = user_email,
user_phone_number = self.request.POST.get('user_phone_number'),
user_device_id = request.META.get('HTTP_DEVICE', ''),
lat = self.request.POST.get('lat'),
lng = self.request.POST.get('lng'),
user_address = self.request.POST.get('user_address'),
creation_date = timezone.now,
email_status = email_stat,
email_score = email_scor,
valid_email = email_valid,
fraud = frau
)
NewEmail.save()
serializer = EmailSerializer(NewEmail)
return Response(serializer.data)
I have receive the folowing JSON response:
{
"user_email": "meloadik#gmail.com",
"user_phone_number": 8117904544,
"user_device_id": "",
"lat": "20.9750000000000000",
"lng": "89.6141400000000000",
"user_address": "rfm mz5 lt4",
"creation_date": "2022-08-23T22:47:13.687178Z",
"email_status": null,
"email_score": 0,
"valid_email": 0,
"fraud": 0
}
I want to know how to format the JSON response differently, like this:
{
"email_response": {
"user_email": "carl#trully.ai",
"creation_date": "2020/06/01",
"email_status": "active",
"email_score": 910,
"valid_email": 1,
"fraud": 0
},
"phone_response": {
"user_phone_number": 8117904544,
}
}
Or modify my JSON Response with different types of styles, tabs, spaces, etc...
A quick fix would be to override EmailSerializer's to_representation method to something like this (pseudocode):
def to_representation(self, instance):
representation = super(EmailSerializer, self).to_representation(instance)
new_representation = {}
new_representation['email_response'] = {field: representation.get(field) for field in email_fields}
new_representation['phone_response'] = {field: representation.get(field) for field in phone_fields}
return new_representation
My models of Employee registration is as follow.
class EmployeeRegistration(models.Model):
#Departmental Details
EmpId = models.IntegerField(verbose_name='EmpId')
EmpImage = models.ImageField(default='default.png',upload_to='profile_pic/%Y/%m/%d')
EmpSafetyCard= models.ImageField(default='default.png',upload_to='profile_pic/%Y/%m/%d')
Site = models.ForeignKey(Site,on_delete=models.CASCADE,max_length=150,verbose_name='Site')
Department = models.ForeignKey(Department,on_delete=models.CASCADE,max_length=150,verbose_name='Department')
Category = models.ForeignKey(Category,on_delete=models.CASCADE,max_length=150,verbose_name='Category')
Designation = models.ForeignKey(Designation,on_delete=models.CASCADE,max_length=150,verbose_name='Designation')
PfApplicable = models.BooleanField(default = True,verbose_name='Pf Applicable')
EsiApplicable = models.BooleanField(default = True,verbose_name='Esic Applicable')
Uan = models.PositiveIntegerField(null = True,verbose_name='Uan')
Esic = models.PositiveIntegerField(null = True,verbose_name='Esic')
AttendenceAward = models.BooleanField(default = True)
AttendenceAllowance = models.BooleanField(default = True)
ProfesionalTax = models.BooleanField(default = False)
Name = models.CharField(max_length=150,verbose_name='Name')
Father = models.CharField(max_length=150,verbose_name='Father')
Dob = models.DateField()
Male = models.BooleanField(default = True)
Female = models.BooleanField(default = False)
MaritalStatus = models.BooleanField(default = True)
Address = models.CharField(max_length=200,verbose_name='Address')
Aadhar = models.PositiveIntegerField(null=True)
pan = models.CharField(max_length=10)
choices = [('Working','WORKING'),('NotWorking','NOT WORKING'),('Leave','Leave')]
Status = models.CharField(choices=choices,blank = False,max_length=10,verbose_name='Status')
Doj = models.DateField(default = date.today)
Doe = models.DateField(blank = True,verbose_name = 'Doe',null = True)
def __str__(self):
return f'{self.Name}({self.EmpId})'
def save(self):
super().save()
empimg = Image.open(self.EmpImage.path)
empsafetycard = Image.open(self.EmpSafetyCard.path)
if empimg.height>300 or empimg.width>300:
output_size = (300,300)
empimg.thumbnail(output_size)
empimg.save(self.EmpImage.path)
if empsafetycard.height>300 or empsafetycard.width>300:
output_size = (300,300)
empsafetycard.thumbnail(output_size)
empsafetycard.save(self.EmpSafetyCard.path)
This is my newEmployeeForm code
class newEmployeeForm(forms.ModelForm):
class Meta:
model = EmployeeRegistration
fields = '__all__'
labels ={
'EmpImage':'Upload Employee Image',
'EmpSafetyCard':'Upload Safety Card',
'Dob':'Date of Birth',
'Doj':'Date of Joining',
'Doe':'Date of Exit'
}
widgets = {
'Dob':DateInput(),
'Doj': DateInput(),
'Doe': DateInput()
}
This is my View for regitering new employee
def registration_view(request,id=0):
form = newEmployeeForm()
record = RecordsId.objects.all()
empid = 0
for data in record:
empid = data.EmpId
emp_id = empid+1
if(empid!=0 or empid==0):
get_emp = RecordsId.objects.get(EmpId=empid)
EmployeeId={"EmpId":emp_id}
print(request.POST)
if(request.method == 'POST'):
if(id==0):
form = newEmployeeForm(request.POST or None,request.FILES,initial=EmployeeId)
print("id= 0")
else:
print(id)
employee = EmployeeRegistration.objects.get(pk=id)
form = newEmployeeForm(instance=employee)
if form.is_valid():
print("valid")
get_emp.EmpId = emp_id
get_emp.save()
form.save()
print("saved")
form = newEmployeeForm(initial=EmployeeId)
messages.success(request,'Successfully Updated')
return redirect('emplist')
else:
print("Form is not valid")
context = {
'form':form,
"contact":"active"
}
return render(request,"employee/NewEmployee.html",context)
I have a view for registering new employee at the same time in the same view i am updating the records of employee. But when i am trying to update the existing record. It is creating new record. i don't know why this is happening. Please help me.
I have a detail page of clinical operation. And i want to make it accessible for only staff's and doctor's related with this operation with ManyToManyField
For do this i did
class OperationPanelView(LoginRequiredMixin,View):
login_url = reverse_lazy("doctor:login")
def get(self,request,id):
operation = OperationModel.objects.get(id=id)
if request.user.user_doctors not in operation.doctor.all():
if DoctorModel.objects.filter(user = request.user).exists():
return redirect("doctor:panel",request.user.id)
elif request.user.is_staff == True:
return redirect("disease:panel",operation.id)
context = {
"operation":operation,
}
return render(request,"operation_detail.html",context)
this has worked for if request.user.user_doctors is not related with this operation's doctors then it will redirects the user to their own panel.
And also has worked for if request.user.user_doctors is related with operation's doctors then page will open.
But didn't worked for if user is staff and gave this error:
RelatedObjectDoesNotExist at /disease/panel/1
CustomUserModel has no user_doctors.
in line 35: if request.user.user_doctors not in operation.doctor.all():
Then i add this condition:
if request.user.user_doctors:
but this gave the same error too
DoctorModel:
class DoctorModel(models.Model):
BLOOD_TYPE_CHOICES = [
("A+","A+"),
("A-","A-"),
("B+","B+"),
("B-","B-"),
("O+","O+"),
("O-","O-"),
("AB+","AB+"),
("AB-","AB-"),
]
GENDER_CHOICES = [
("Male","Male"),
("Female","Female"),
]
user = models.OneToOneField("account.CustomUserModel",on_delete=models.CASCADE,null=False,blank=False,related_name="user_doctors")
first_name = models.CharField(verbose_name="Ad:",max_length=40,null=False,blank=False)
last_name = models.CharField(verbose_name="Soyad:",max_length=60,null=False,blank=False)
gender = models.CharField(choices=GENDER_CHOICES,max_length=6)
working_field = models.ForeignKey(DoctorField,on_delete=models.SET_NULL,null=True,blank=False,related_name="field_doctors")
phonenumber = PhoneNumberField(null=False,blank=True)
about = models.TextField(verbose_name="Haqqinda:",null=True,blank=True)
is_active = models.BooleanField(default=True)
blood_type=models.CharField(choices=BLOOD_TYPE_CHOICES,max_length=10, null=True,blank=False)
born_date = models.DateField(null=True,blank=False)
OperationModel:
class OperationModel(models.Model):
name = models.CharField(null=True,blank=True,max_length=45)
description = models.TextField(null=True,blank=True)
disease = models.ManyToManyField(DiseaseModel,related_name="disease_operations")
doctor = models.ManyToManyField("doctors.DoctorModel",blank=False,related_name="doctor_operations")
starting_date = models.DateTimeField(auto_now_add=True)
finished_date = models.DateTimeField(auto_now=True)
patient = models.ForeignKey("patients.PatientModel",on_delete=models.DO_NOTHING,related_name="patient_operations")
is_active = models.BooleanField(default=True)
CustomUserModel:
class CustomUserModel(AbstractUser):
username = None
is_accepted = models.BooleanField(default=False)
email = models.EmailField(_("email address"),unique=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
objects = CustomUserManager()
class Meta:
db_table = "user"
I'm trying to create a new function but I'm getting this Django error :
'SocieteIntervention' object has no attribute 'update'
I have several models in my application :
class Societe(models.Model):
Nom = models.CharField(null= False, max_length=30, verbose_name='Nom de Société')
Etat = models.CharField(max_length = 30, choices = CHOIX_ETAT_SOCIETE, null=False, verbose_name="Etat")
Adresse = models.CharField(max_length=30, verbose_name='Adresse')
Ville = models.CharField(max_length=30, verbose_name='Ville')
Zip = models.IntegerField(verbose_name='Code Postal')
Region = models.CharField(max_length=30, verbose_name='Région')
Pays = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays')
Mail = models.CharField(max_length=40, verbose_name='Email')
Web = models.CharField(max_length=40, verbose_name='Site Web')
Telephone = models.CharField(max_length=20, verbose_name='Téléphone Fixe')
Fax = models.CharField(max_length=20, verbose_name='Fax')
SIREN = models.BigIntegerField(verbose_name='N° SIREN')
SIRET = models.BigIntegerField(verbose_name='N° SIRET')
NAF_APE = models.CharField(max_length=5, verbose_name='Code NAF-APE')
RCS = models.CharField(max_length = 30, verbose_name='Code RCS')
CHOIX_TVA = models.CharField(max_length = 30, choices=CHOIX_TVA, verbose_name='Assujeti à la TVA')
TVA = models.CharField(max_length=13, verbose_name='N° TVA Intracommunautaire')
Type = models.CharField(max_length = 30, choices = CHOIX_SOCIETE, verbose_name = 'Type de Société')
Effectif = models.CharField(max_length = 30, choices = CHOIX_EFFECTIF, verbose_name = 'Effectif')
Capital = models.IntegerField(verbose_name = 'Capital de la Société (euros)')
Creation = models.DateTimeField(auto_now_add=True)
InformationsInstitution = models.CharField(max_length=30, null=False, verbose_name='Informations Institution')
Utilisateur = models.CharField(max_length=100, null=False, verbose_name="Utilisateur", default=" ")
def save(self, *args, **kwargs):
for field_name in ['Nom', 'Ville', 'Region']:
val = getattr(self, field_name, False)
if val:
setattr(self, field_name, val.upper())
super(Societe, self).save(*args, **kwargs)
class SocieteContrat(models.Model):
Societe = models.ForeignKey(Societe, related_name="Societe", verbose_name="Société")
PointsTotal = models.FloatField(verbose_name="Nombre points total")
PointsRestant = models.FloatField(verbose_name="Nombre points restants", null=True)
def __unicode__(self):
return unicode (self.id, self.Societe, self.PointsTotal, self.PointsRestant)
class SocieteIntervention(models.Model):
Societe = models.ForeignKey(Societe, related_name="Societe1", verbose_name="Société")
Date = models.DateField(verbose_name="Date de l'Intervention")
Temps = models.IntegerField(verbose_name="Durée Intervention (min)")
Description = models.CharField(max_length=200, verbose_name="Description")
Niveau = models.CharField(max_length = 30, choices = CHOIX_NIVEAU, verbose_name = 'Niveau Intervention/Intervenant')
PointsConsommes = models.FloatField(verbose_name=u"Nombre points consommés", null=True)
class CoefficientIntervention(models.Model):
Technicien = models.FloatField(verbose_name="Coefficient Technicien")
Ingenieur = models.FloatField(verbose_name="Coefficient Ingénieur")
Consultant = models.FloatField(verbose_name="Coefficient Consultant")
Architecte = models.FloatField(verbose_name="Coefficient Architecte")
def __unicode__(self):
return unicode (self.id, self.Technicien, self.Ingenieur, self.Consultant, self.Architecte)
My objective is : Create service contracts with a number of points. Points are deducted according to a coefficient. This coefficient depending on your status : Technician, Engineer, ...
I create this function in my view :
#login_required
def Identity_Contrat(request, id) :
societe = get_object_or_404(Societe, pk=id)
contrat = get_object_or_404(SocieteContrat, pk=id)
coefficient = CoefficientIntervention.objects.last()
if request.method == 'POST':
form = InterventionFormulaire(request.POST or None)
if form.is_valid() :
post = form.save()
Liste_Intervention = SocieteIntervention.objects.filter(Societe__id=id).values_list("Temps")
Value = Liste_Intervention.last()[0]
Type_Intervention = SocieteIntervention.objects.filter(Societe__id=id).values_list("Niveau")
if Type_Intervention.last() == (u'Ing\xe9nieur',) :
Consomme = Value * coefficient.Ingenieur
elif Type_Intervention.last() == ('Technicien',) :
Consomme = Value * coefficient.Technicien
elif Type_Intervention.last() == ('Consultant',) :
Consomme = Value * coefficient.Consultant
elif Type_Intervention.last() == ('Architecte',) :
Consomme = Value * coefficient.Architecte
PointsConsommes = SocieteIntervention.objects.latest('id').update(PointsConsommes=Consomme)
messages.success(request, 'Le formulaire a été enregistré !')
return HttpResponseRedirect('http://localhost:8000/Identity/Contrat/Societe/'+id)
else:
messages.error(request, "Le formulaire est invalide !")
else:
form = InterventionFormulaire()
context = {
"coefficient" : coefficient,
"societe" : societe,
"contrat" : contrat,
"form" : form,
}
return render(request, 'Identity_Societe_Contrat.html', context)
I fill the form, I save it with PointsConsommes == NULL,then I'm trying to update it with the value calculated previously.
How I can update the field PointsConsommes when the form is saved ? I don't overcome to update it with .update.
You can try to use update_fields:
PointsConsommes = SocieteIntervention.objects.latest('id')
PointsConsommes.PointsConsommes = Consomme
PointsConsommes.save(update_fields=['PointsConsommes'])
Hi I'm trying to populate my django app with data from a dbf file , I'm trying to make objects , as taught in the djangobook
>>> p = Publisher(name='Apress',
address='2855 Telegraph Ave.',
city='Berkeley',
state_province='CA',
country='U.S.A.',
website='http://www.apress.com/')
>>> p.save()
How can I add foreign keys and many to many keys this way ?
Or probably a better approach? dbf files have thousands of rows , so updating data by hand wouldn't be a viable approach.
Here's my models.py as suggested , almoust every model includes a foreign key , or a many to many field , I'm kind of stuck , because of filling them , I'm using dbf2py library to read the foxpro databases, and want to make a script for exporting the data
thanks in advance
from __future__ import unicode_literals
from django.db import models
class Terminos_pago(models.Model):
terminos = models.CharField(max_length = 20)
def __unicode__(self):
return self.terminos
class Clientes(models.Model):
"""docstring for Clientes"""
nombre = models.CharField(max_length=40)
direccion = models.CharField(max_length=70)
estado = models.CharField(max_length=16)
ciudad = models.CharField(max_length=30)
cp = models.IntegerField()
kilometros= models.IntegerField()
rfc = models.CharField(max_length=13 , null = True)
horas = models.DecimalField(null = True,decimal_places = 2 , max_digits = 5)
terminos_pago = models.ForeignKey(Terminos_pago,null=True)
dias_de_credito = models.IntegerField(blank = True , null = True)
def __unicode__(self):
return u'%s %s' % (self.nombre , self.horas)
class Contactos(models.Model):
"""docstring for Contactos"""
nombre = models.CharField(max_length=30)
departamento = models.CharField(max_length=16)
telefono = models.CharField(max_length = 16)
extension = models.IntegerField()
email = models.EmailField(blank = True)
cliente = models.ForeignKey(Clientes)
def __unicode__(self):
return self.nombre
class Maquinas(models.Model):
"""docstring for Maquinas"""
contacto = models.ForeignKey(Contactos , null = True)
id_usuario = models.CharField(max_length=13 , null = True , blank = True)
fabricante = models.CharField(max_length=15 )
no_serie = models.CharField(max_length=10 )
modelo = models.CharField(max_length=10 )
rango_x = models.IntegerField()
rango_y = models.IntegerField()
rango_z = models.IntegerField()
mppl = models.IntegerField()
mppe = models.IntegerField()
probe_type = models.CharField(max_length=10 )
probe_head = models.CharField(max_length=16)
probe_serial = models.CharField(max_length=15 )
extension = models.IntegerField( blank = True , null = True)
version_software=models.CharField(max_length=15)
version_firmware=models.CharField(max_length=15)
controlador = models.CharField(max_length=10)
accesorios = models.CharField(max_length=15 , null = True , blank = True)
driver_software= models.CharField(max_length=15)
modelo_computadora=models.CharField(max_length=10)
fecha_fabricacion = models.DateField(blank=True , null = True)
diametro_stylus= models.IntegerField()
def __unicode__(self):
return u'%s %s %s %s ' % (self.modelo , self.fabricante , self.contacto.nombre , self.contacto.cliente.nombre)
class Servicios(models.Model):
"""docstring for Servicios"""
servicio = models.CharField(max_length = 20)
def __unicode__(self):
return self.servicio
class ListaPrecios(models.Model):
"""docstring for ListaPrecios"""
fecha = models.DateField(null = True)
horas = models.IntegerField()
horas_extra = models.IntegerField()
horas_viaje = models.IntegerField(null = True)
kilometros = models.IntegerField()
hotel = models.IntegerField()
manuales = models.IntegerField()
traslados = models.IntegerField()
avion = models.IntegerField()
sobre_equipaje = models.IntegerField()
renta_auto = models.IntegerField()
papeleria = models.IntegerField()
def __unicode__(self):
return str(self.fecha)
class Ingenieros(models.Model):
"""docstring for Ingenieros"""
nombre = models.CharField(max_length=20)
referencia = models.CharField(max_length=4)
telefono = models.CharField(max_length = 16)
email = models.EmailField(null = True)
def __unicode__(self):
return self.nombre
class Cotizacion(models.Model):
"""docstring for Cotizacion"""
fecha = models.DateField()
contacto = models.ForeignKey(Contactos , null = True)
servicio = models.ManyToManyField(Servicios)
maquinas = models.ManyToManyField(Maquinas)
horas = models.IntegerField()
horas_extra = models.IntegerField(blank=True ,null = True)
#horas_viaje = models.IntegerField()
viajes = models.IntegerField()
hotel = models.IntegerField(blank=True ,null = True)
manuales = models.IntegerField(blank=True ,null = True)
traslados = models.IntegerField( blank=True ,null = True)
aviones = models.IntegerField(blank=True ,null = True)
sobre_equipaje = models.IntegerField(blank=True ,null = True)
renta_auto = models.IntegerField(blank=True ,null = True)
papeleria = models.IntegerField(blank=True ,null = True)
importe = models.IntegerField(blank = True , null = True)
iva = models.DecimalField(decimal_places = 2 , max_digits = 5 ,blank = True , default = 0.16)
observaciones = models.CharField(blank=True ,max_length = 255, null = True)
SA = models.NullBooleanField()
tipo_cambio = models.DecimalField(decimal_places = 2 , max_digits = 5, blank = True , null = True)
def __unicode__(self):
return u'%s %s %s %s' % (self.fecha , self.contacto.cliente.nombre , self.contacto.nombre ,self.servicio)
class Ordenes_de_servicio(models.Model):
"""docstring for Ordenes_de_trabajo"""
fecha = models.DateField(null = True)
ingeniero = models.ManyToManyField(Ingenieros)
observaciones = models.CharField(max_length = 255,null = True , blank = True)
viaticos = models.IntegerField()
orden_compra = models.CharField(max_length = 15)
orden_compra_interna = models.IntegerField(blank = True , null = True)
fecha_servicio = models.DateField(null = True)
viaticos_pagados = models.NullBooleanField()
cotizacion = models.ForeignKey(Cotizacion,null = True)
mail_enviado = models.IntegerField(null=True,blank=True,default=0)
fecha_mail_enviado = models.DateField(null=True , blank = True)
contacto_servicio = models.ForeignKey(Contactos , null = True )
def __unicode__(self):
return u'%s %s' % (self.fecha,self.ingeniero)
class Factura(models.Model):
"""docstring for Factura"""
fecha = models.DateField()
orden_servicio = models.ForeignKey(Ordenes_de_servicio)
descripcion = models.CharField(max_length=255,null = True , blank = True)
pagada = models.NullBooleanField()
def __unicode__(self):
return u'%s %s %s' % (self.orden_servicio.cotizacion.contacto.cliente.nombre , self.orden_servicio , self.fecha)
try and include your models.py, while you do that take a look at One-toMany for Many-to-many relationship
When you define a relationship in a model (i.e., a ForeignKey, OneToOneField, or ManyToManyField), instances of that model will have a convenient API to access the related object(s).
Using the models for example, an Entry object e can get its associated Blog object by accessing the blog attribute: e.blog.
(Behind the scenes, this functionality is implemented by Python descriptors. This shouldn’t really matter to you)
Django also creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Blog object b has access to a list of all related Entry objects via the entry_set attribute: b.entry_set.all().
This is directly from the link i gave above, so visit the link and read deep
If a model has a ForeignKey, instances of that model will have access to the related (foreign) object via a simple attribute of the model.
Example:
>>> e = Entry.objects.get(id=2)
>>> e.blog # Returns the related Blog object.
You can get and set via a foreign-key attribute. As you may expect, changes to the foreign key aren’t saved to the database until you call save(). Example:
>>> e = Entry.objects.get(id=2)
>>> e.blog = some_blog
>>> e.save()