I want to copy data from a model to another model, I found an example Copy Model Object From a Model To Another In Django but I'm getting an error:
AttributeError: 'BigAutoField' object has no attribute 'wid'.
I want wid in the tobjects model to get the Id from w_orders model. This is my code:
models.py
class w_orders(models.Model):
Id = models.BigAutoField(primary_key=True)
datedefwo = models.DateField(default=datetime.now)
datesched = models.DateField(blank=True, null=True)
datefinished = models.DateField(blank=True, null=True)
sign = models.BigIntegerField(blank=True, null=True)
statusid = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES)
typeid = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES)
comments = models.CharField(max_length=254, blank=True, null=True)
navid = models.BigIntegerField(blank=True, null=True)
navkonsid = models.CharField(max_length=12, blank=True, null=True)
navname = models.CharField(max_length=254, blank=True, null=True)
navcustadr = models.CharField(max_length=254, blank=True, null=True)
navdebt = models.FloatField(blank=True, null=True)
navpropcode = models.CharField(max_length=254, blank=True, null=True)
navdepcode = models.CharField(max_length=254, blank=True, null=True)
navphoneno = models.CharField(max_length=254, blank=True, null=True)
navreasoncomp = models.CharField(max_length=254, blank=True, null=True)
nightshift = models.BooleanField(default=False)
priority = models.BigIntegerField(blank=True, null=True)
stid = models.BigIntegerField(blank=True, null=True)
mapurl = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.Id
def save(self, *args, **kwargs):
super(w_orders, self).save(*args, **kwargs)
newob = tobjects()
...
newob.save()
class tobjects(models.Model):
oid = models.BigAutoField(primary_key=True)
wid = models.ForeignKey(w_orders, on_delete=models.CASCADE)
objtypegisid = models.BigIntegerField(blank=True, null=True, default=1)
objgisid = models.BigIntegerField(blank=True, null=True, default=1)
condgenid = models.BigIntegerField(blank=True, null=True, default=1)
condriskid = models.BigIntegerField(blank=True, null=True, default=1)
condratsid = models.BigIntegerField(blank=True, null=True, default=1)
condmhcoverid = models.BigIntegerField(blank=True, null=True, default=1)
condmhwallid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydrsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydreid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvolsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvoleid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconssid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconseid = models.BigIntegerField(blank=True, null=True, default=1)
txt = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.oid
class w_orders(models.Model):
Id = models.BigAutoField(primary_key=True)
datedefwo = models.DateField(default=datetime.now)
datesched = models.DateField(blank=True, null=True)
datefinished = models.DateField(blank=True, null=True)
sign = models.BigIntegerField(blank=True, null=True)
statusid = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES)
typeid = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES)
comments = models.CharField(max_length=254, blank=True, null=True)
navid = models.BigIntegerField(blank=True, null=True)
navkonsid = models.CharField(max_length=12, blank=True, null=True)
navname = models.CharField(max_length=254, blank=True, null=True)
navcustadr = models.CharField(max_length=254, blank=True, null=True)
navdebt = models.FloatField(blank=True, null=True)
navpropcode = models.CharField(max_length=254, blank=True, null=True)
navdepcode = models.CharField(max_length=254, blank=True, null=True)
navphoneno = models.CharField(max_length=254, blank=True, null=True)
navreasoncomp = models.CharField(max_length=254, blank=True, null=True)
nightshift = models.BooleanField(default=False)
priority = models.BigIntegerField(blank=True, null=True)
stid = models.BigIntegerField(blank=True, null=True)
mapurl = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.Id
class tobjects(models.Model):
oid = models.BigAutoField(primary_key=True)
wid = models.ForeignKey(w_orders, on_delete=models.CASCADE)
objtypegisid = models.BigIntegerField(blank=True, null=True, default=1)
objgisid = models.BigIntegerField(blank=True, null=True, default=1)
condgenid = models.BigIntegerField(blank=True, null=True, default=1)
condriskid = models.BigIntegerField(blank=True, null=True, default=1)
condratsid = models.BigIntegerField(blank=True, null=True, default=1)
condmhcoverid = models.BigIntegerField(blank=True, null=True, default=1)
condmhwallid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydrsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydreid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvolsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvoleid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconssid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconseid = models.BigIntegerField(blank=True, null=True, default=1)
txt = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.oid
#receiver(post_save, sender=w_orders)
def ensure_order_exists(sender, **kwargs):
if kwargs.get('created', False):
tobjects.objects.get_or_create(wid=kwargs.get('instance'))
for o in w_orders.objects.all():
t = tobjects.create(wid=o)
t.save()
Also possible is bulk_create which is faster but only works with PostgreSQL (please read https://docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create):
tobjects.objects.bulk_create([tobjects(wid=o) for o in w_orders.objects.all()])
Please consider PEP 8 for your code. It's horrible to read.
Related
Ok, so I have this application where the users make an order for a Category through the app. Every category contains products. And what I want to do is when a product is issued to the user the order status for the order made by the user should change from 1(approved) to 4(issued) and the product name should be added in the order table to confirm the product that was issued to that request.
How do I do that in Django? Below are my models
class Category(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Product(models.Model):
pro_name = models.CharField(max_length=100, blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
issue_to = models.ForeignKey('Order',default='', on_delete=models.CASCADE,blank=True, null=True)
serial_num = models.CharField(max_length=100, blank=True, null=True)
model_num = models.CharField(max_length=100, blank=True, null=True)
storage_size = models.CharField(max_length=50, blank=True, null=True)
memory_size = models.CharField(max_length=50, blank=True, null=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, blank=True, null=True)
receive_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_by = models.CharField(max_length=50, blank=True, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=False, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Order(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
pro_name = models.ForeignKey(Product, on_delete=models.CASCADE, null=True,related_name='product')
staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
order_quantity = models.PositiveIntegerField(null=True)
department = models.CharField(max_length=50, choices=DEPARTMENT, null=True)
order_status = models.IntegerField(default=0)
approve_quantity = models.IntegerField(default='1', blank=True, null=True)
transaction_id = models.CharField(default=uuid.uuid4().hex[:8].upper(), max_length=50, editable=False)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
Currently what I do is after a particular product has been issued to a user I have to go to the order table and change the order status to 4(issued) which is hectic especially when the orders are plenty.
class Services(models.Model):
id = models.BigAutoField(primary_key=True)
medical_unit = models.ForeignKey(MedicalUnits, models.DO_NOTHING, related_name='services_medical_unit',
blank=True, null=True)
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
name = models.CharField(max_length=500, blank=True, null=True)
billing_code = models.CharField(max_length=500, blank=True, null=True)
department_id = models.IntegerField(blank=True, null=True)
assignable_type = models.CharField(max_length=500, blank=True, null=True)
assignable_id = models.BigIntegerField(blank=True, null=True)
department_service_id = models.IntegerField(blank=True, null=True)
user_id = models.IntegerField(blank=True, null=True)
is_active = models.BooleanField(blank=True, null=True)
ward_id = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'services'
class PackageServices(models.Model):
id = models.BigAutoField(primary_key=True)
billing_package = models.ForeignKey(BillingPackages, models.DO_NOTHING, blank=True, null=True)
assignable_type = models.CharField(max_length=500, blank=True, null=True)
assignable_id = models.BigIntegerField(blank=True, null=True)
quantity = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
class Meta:
managed = False
db_table = 'package_services'
I want To access "PackageService" Through "Services".
My branch model has 4 primary keys which are unique together: ('branch_short_name', 'partner_short_name', 'tenant', 'contributor'). I would like to be able to create/ POST some objects with similar
'branch_short_name', 'partner_short_name', 'tenant' but then with a unique 'contributor'.
When doing that I get a 400 bad request error in postman. I don't know where the problem lies, in the model or in the serializer.
models.py
class Branch(models.Model):
additional_address1 = models.CharField(max_length=255, blank=True, null=True)
additional_address2 = models.CharField(max_length=255, blank=True, null=True)
branch_number = models.CharField(max_length=255, blank=True, null=True)
branch_short_name = models.CharField(primary_key=True, max_length=255)
building = models.CharField(max_length=255, blank=True, null=True)
city = models.CharField(max_length=255, blank=True, null=True)
end_date = models.DateTimeField(blank=True, null=True)
country_code = models.CharField(max_length=255, blank=True, null=True)
created = models.DateTimeField(blank=True, null=True)
display_name = models.CharField(max_length=255, blank=True, null=True)
display_web = models.BooleanField(blank=True, null=True)
district = models.CharField(max_length=255, blank=True, null=True)
file_origin_date = models.DateTimeField(blank=True, null=True)
filename = models.CharField(max_length=255, blank=True, null=True)
floor = models.CharField(max_length=255, blank=True, null=True)
business_name = models.CharField(max_length=255, blank=True, null=True)
house_number = models.CharField(max_length=255, blank=True, null=True)
import_file_number = models.BigIntegerField(blank=True, null=True)
contributor = models.CharField(max_length=255)
job_id = models.CharField(max_length=255, blank=True, null=True)
latitude = models.FloatField(blank=True, null=True)
longitude = models.FloatField(blank=True, null=True)
start_date = models.DateTimeField(blank=True, null=True)
branch_hours = models.CharField(max_length=255, blank=True, null=True)
po_box = models.CharField(max_length=255, blank=True, null=True)
province = models.CharField(max_length=255, blank=True, null=True)
region = models.CharField(max_length=255, blank=True, null=True)
remarks = models.CharField(max_length=255, blank=True, null=True)
street = models.CharField(max_length=255, blank=True, null=True)
tenant = models.CharField(max_length=255)
updated = models.DateTimeField(blank=True, null=True)
zip_code = models.CharField(max_length=255, blank=True, null=True)
ranking = models.FloatField()
branch_type = models.IntegerField(blank=True, null=True)
branch_contact_text1 = models.CharField(max_length=255, blank=True, null=True)
branch_contact_text2 = models.CharField(max_length=255, blank=True, null=True)
phone_number = models.CharField(max_length=255, blank=True, null=True)
email_address = models.CharField(max_length=255, blank=True, null=True)
website = models.CharField(max_length=500, blank=True, null=True)
branch_hours_osm = models.CharField(max_length=400, blank=True, null=True)
partner_short_name = models.ForeignKey('Partner', models.DO_NOTHING, db_column='partner_short_name')
features = models.TextField(blank=True, null=True) # This field type is a guess.
marketing_attribute_short_names = models.TextField(blank=True, null=True) # This field type is a guess.
marketing_attribute_values = models.TextField(blank=True, null=True) # This field type is a guess.
class Meta:
managed = False
db_table = 'branch'
unique_together = (('branch_short_name', 'partner_short_name', 'tenant', 'contributor'),)
serializers.py
class BranchSerializer(serializers.ModelSerializer):
class Meta:
model = Branch
fields = '__all__'
views.py
#api_view(['GET', 'POST', 'DELETE'])
def branch_list(request):
# GET list of branchs, POST a new branch, DELETE all branchs
if request.method == 'GET':
branchlist = Branch.objects.all()[:10]
branchlist_serializer = BranchSerializer(branchlist, many=True)
return JsonResponse(branchlist_serializer.data, safe=False)
# 'safe=False' for objects serialization
elif request.method == 'POST':
branch_data = JSONParser().parse(request)
branch_serializer = BranchSerializer(data=branch_data)
if branch_serializer.is_valid():
branch_serializer.save()
return JsonResponse(branch_serializer.data, status=status.HTTP_201_CREATED)
return JsonResponse(branch_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
urls.py
urlpatterns = [
url(r'^api/places$', views.branch_list),
url(r'^api/placescount$', views.branch_count),
url(r'^api/latestimport/(?P<contributor>\D+)$', views.latest_import),
url(r'^api/partners$', views.partner_list),
url(r'^api/partners/(?P<partner_short_name>[0-9]+)$', views.partner_detail),
url(r'^api/places/(?P<branch_short_name>[0-9]+)$', views.branch_detail),
url(r'^api/places/(?P<branch_short_name>[0-9]+)/(?P<contributor>\D+)$' , views.branch_from_contributor),
]
How do I extract the email ID of users from the Users columns? I've managed to make sure that the name of the users are extracted through the Users table.
class Project(models.Model):
STATUS_CHOICE = (
('Project Manager', 'Project Manager'),
('Technician', 'Technician'),
('Tester', 'Tester')
)
STATUS_CHOICE_1 = (
('Work Assigned', 'Work Assigned'),
('Work in Progress', 'Work in Progress'),
('Testing', 'Testing'),
('Completed', 'Completed')
)
project_name = models.CharField(max_length=100)
project_description = models.CharField(max_length=100)
Admin_Name = models.CharField(max_length=100)
Admin_Mail_ID = models.EmailField(max_length=50)
Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Project_Manager_1_users")
Project_Manager_1_Mail_ID = models.EmailField(max_length=50)
Project_Manager_2 = models.CharField(max_length=50, blank=True, null=True)
Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Technician_1_users")
Technician_1_Mail_ID = models.EmailField(max_length=50)
Technician_2 = models.CharField(max_length=50, blank=True, null=True)
Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_3 = models.CharField(max_length=50, blank=True, null=True)
Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Tester_1 = models.CharField(max_length=50, blank=True, null=True)
Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example#gmail.com')
Additional_User_1 = models.CharField(max_length=50, blank=True, null=True)
Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_2 = models.CharField(max_length=18, blank=True, null=True)
Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_3 = models.CharField(max_length=18, blank=True, null=True)
Additional_User_3_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE_1)
Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
Finish_Date = models.DateTimeField(null=True, blank=True)
Supporting_Documents = models.FileField(null=True, blank=True)
I'm not that great at coding and I would really appreciate all the help I'd get.. Thank you so much everyone..
I have a queryset that gets information from a model and shows it in a template.
datos = RecetaDatosMedicoPaciente.objects.get(pk=id)
what I need is that information, save it in an other model, but I don't know who to do it, 'cause the name of the variables are different.
This are my 2 models I get the info from RecetaDatosMedicoPaciente and I need to save it in proveedores_farmacia.
model.py
class RecetaDatosMedicoPaciente(models.Model):
fecha_receta_2 = models.DateField(auto_now=True)
hora_receta = models.TimeField(auto_now=True)
nombre_medico_3 = models.ForeignKey(Medico, related_name='med', null=True)
fecha_nacimiento_4 = models.DateField(max_length=10, null=True, blank=True)
datosmedicospaciente_credencial = models.CharField(max_length=20, null=False)
nombre_miembro_6 = models.CharField(max_length=60, null=True, blank=True)
apellido_miembro_6 = models.CharField(max_length=60, null=True, blank=True)
edad_Miembro_7 = models.CharField(max_length=10, null=True, blank=True)
sexo_miembro_8 = models.CharField(max_length=20, null=True, blank=True)
empresa_empleadora_9 = models.CharField(max_length=50, null=True, blank=True)
plan_inscrito_10 = models.CharField(max_length=10, null=True, blank=True)
vigencia_receta_11 = models.DateField(max_length=30, null=True, blank=True)
codigo_diagnostico_12 = models.CharField(max_length=250, null=True, blank=True)
codigo_diagnostico_13 = models.CharField(max_length=250, null=True, blank=True)
codigo_diagnostico_14 = models.CharField(max_length=250, null=True, blank=True)
codigo_diagnostico_15 = models.CharField(max_length=250, null=True, blank=True)
codigo_diagnostico_16 = models.CharField(max_length=250, null=True, blank=True)
codigo_diagnostico_17 = models.CharField(max_length=250, null=True, blank=True)
class proveedores_farmacia(models.Model):
farmacia_folio = models.IntegerField(max_length=10, blank=True, null=True);
farmacia_tipocambio = models.IntegerField(max_length=20, blank=True, null=True);
farmacia_nombremiembro = models.CharField(max_length=30, blank=True, null=True);
farmacia_credencial = models.CharField(max_length=30, blank=True, null=True);
farmacia_apellidomiembro = models.CharField(max_length=30, blank=True, null=True);
farmacia_fechasurtido = models.DateField(auto_now=True, blank=True, null=True);
farmacia_horasurtido = models.TimeField(auto_now=True, blank=True, null=True);
farmacia_fechareceto = models.DateField(max_length=20, blank=True, null=True);
farmacia_horareceto = models.TimeField(max_length=20, blank=True, null=True);
farmacia_copago = models.CharField(max_length=20, blank=True, null=True);
farmacia_total = models.CharField(max_length=20, blank=True, null=True);
farmacia_total_copago = models.CharField(max_length=20, blank=True, null=True);
farmacia_diferencia_pago = models.CharField(max_length=20, blank=True, null=True);
You can do this in views or where ever, but you can also set up a new file to do this.
make a new file in the same directory as your model.
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_site.settings")
from your_app_name.models import RecetaDatosMedicoPaciente, proveedores_farmacia
datos = RecetaDatosMedicoPaciente.objects.get(pk=id)
proveedores_create = proveedores_farmacia.objects.create(
farmacia_folio = datos.fecha_receta_2
farmacia_tipocambio = datos.hora_receta
farmacia_nombremiembro = datos.nombre_medico_3
farmacia_credencial = datos.etc
farmacia_apellidomiembro = datos.etc
farmacia_fechasurtido = datos.etc
farmacia_horasurtido = datos.etc
farmacia_fechareceto = datos.etc
farmacia_horareceto = datos.etc
farmacia_copago = datos.etc
farmacia_total = datos.etc
farmacia_total_copago = datos.etc
farmacia_diferencia_pago = datos.etc
)