I have a existed model,which is EmsanWorks(models.Model).
I would like to have a same page model, so I copy a new model and named it EmsanWorksPage and changed models.Model to Page.
class EmsanWorksPage(Page):
id_works = models.AutoField(primary_key=True)
name_r = models.CharField(max_length=255)
name_o = models.CharField(max_length=255)
title_r = models.TextField()
title_o = models.TextField()
title_t = models.TextField()
birth_y = models.CharField(max_length=20)
birth_c = models.ForeignKey(EmsanPays, models.DO_NOTHING, db_column='birth_c',related_name='page_emsanpays_birth_c')
gender = models.CharField(max_length=6)
dest = models.CharField(max_length=255)
media_spec = models.CharField(max_length=255)
year = models.TextField() # This field type is a guess.
commission = models.CharField(max_length=255)
performer = models.CharField(max_length=255)
first_perf = models.CharField(max_length=255)
duration = models.CharField(max_length=255)
perf_c = models.ForeignKey(EmsanPays, models.DO_NOTHING, db_column='perf_c')
context = models.TextField()
instr = models.TextField()
cycle = models.CharField(max_length=255)
media_w = models.CharField(max_length=255)
setup = models.CharField(max_length=255)
prod_loc = models.TextField()
prod_per = models.TextField()
perf_tech = models.TextField()
perf_media = models.TextField()
publisher = models.CharField(max_length=255)
audio = models.CharField(max_length=255)
prog_notes = models.TextField()
reception = models.TextField()
editor = models.CharField(max_length=255)
phono = models.CharField(max_length=255)
comment = models.TextField()
timestamp = models.DateTimeField()
modif = models.TextField()
afficher = models.CharField(max_length=3)
restricted_editors = models.TextField()
class Meta:
managed = False
db_table = 'emsan_works'
However, after migrate I got this error
OperationalError at /admin/emsanapp/emsanworkspage/
(1054, "Unknown column 'emsan_works.page_ptr_id' in 'field list'")
Related
models.py:
class NewJsonData(models.Model):
speed = models.IntegerField()
heading = models.IntegerField()
altitude = models.FloatField()
accuracy = models.FloatField()
longitude = models.FloatField()
altitudeAccuracy = models.FloatField(null=True)
latitude = models.FloatField()
pass
class NewApiJsonData(models.Model):
_id = models.CharField(null=True, max_length=100)
coords = models.ForeignKey(
NewJsonData, on_delete=models.CASCADE, null=True, blank=True)
mocked = models.BooleanField()
timestamp = models.FloatField()
_v = models.IntegerField(null=True)
createdAt = models.CharField(null=True, max_length=100)
updatedAt = models.CharField(null=True, max_length=100)
I was trying to create a new table having contents of both models as seen in below picture.
Table of NewJsonData looks as:
and table of NewApiJsonData looks as:
You can inherit one model to another in django
class NewJsonData(models.Model):
speed = models.IntegerField()
heading = models.IntegerField()
altitude = models.FloatField()
accuracy = models.FloatField()
longitude = models.FloatField()
altitudeAccuracy = models.FloatField(null=True)
latitude = models.FloatField()
class NewApiJsonData(NewJsonData): #inherit above model
_id = models.CharField(null=True, max_length=100)
coords = models.ForeignKey(
NewJsonData, on_delete=models.CASCADE, null=True, blank=True)
mocked = models.BooleanField()
timestamp = models.FloatField()
_v = models.IntegerField(null=True)
createdAt = models.CharField(null=True, max_length=100)
updatedAt = models.CharField(null=True, max_length=100)
so the resulting NewApiJsonData contains the fields of NewJsonData
These are classes. Use multiple inheritance, if you know there will be no conflicts:
class Combined(NewJsonData, NewApiJsonData):
pass
My model
class Ad_company(models.Model):
idx = models.AutoField(primary_key=True)
subject = models.CharField(max_length=255)
memo = models.CharField(max_length=255)
content = models.TextField()
is_display = models.CharField(max_length=1)
writer = models.CharField(max_length=255)
write_date = models.DateTimeField()
update_date = models.DateTimeField()
delete_date = models.DateTimeField()
deadline_date = models.DateTimeField()
reply = models.IntegerField(blank=True)
hits = models.IntegerField(blank=True)
ad_apply = models.IntegerField(blank=True)
ad_category1 = models.CharField(max_length=255)
ad_category2 = models.CharField(max_length=255)
ad_place = models.CharField(max_length=255)
ad_age = models.CharField(max_length=255)
ad_sex = models.CharField(max_length=255)
ad_budget = models.BigIntegerField()
ad_length = models.CharField(max_length=255)
is_done = models.CharField(max_length=1)
is_pay = models.CharField(max_length=1)
ad_service = models.CharField(max_length=255)
ad_object = models.CharField(max_length=255)
is_file = models.CharField(max_length=1)
ad_require = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'ad_write_company'
class Ad_company_apply(models.Model):
idx = models.AutoField(primary_key=True)
parent_idx = models.IntegerField()
username = models.CharField(max_length=255)
content = models.TextField()
date = models.DateTimeField(default=datetime.now, blank=True)
budget = models.BigIntegerField()
term = models.IntegerField()
is_done = models.CharField(max_length=1)
SELECT * FROM ad_write_company INNER JOIN ad_write_company_apply ON ad_write_company.idx = ad_write_company_apply.parent_idx where ad_write_company_apply.is_done = 1 and ad_write_company_apply.username = 'asdffdsa'
This is my query. but I can not make join query with orm.
Sorry for question is too short.
And Is my query right?
I not sure of that. Thanks for answer.
or do you guys have other good idea?
I would advise to work with a ForeignKey from Ad_company_apply to Ad_company. This makes it easier to generate queries in Django and will guarantee referential integrity.
It thus makes sense to rewrite the Ad_company_apply model to:
class Ad_company_apply(models.Model):
# …
parent_idx = models.ForeignKey(
Ad_company,
db_column='parent_idx',
on_delete=models.CASCADE
)
# …
In that case, you can .filter(…) [Django-doc] with:
Ad_Company.objects.filter(ad_company_appy__isdone=1, ad_company_appy__username='asdffdsa')
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from Ad_company to AdCompany.
I use sqlite.
class Member(models.Model):
member_id = models.AutoField(primary_key=True)
is_update = models.IntegerField(default=0)
member_name = models.CharField(max_length=50)
member_group = models.IntegerField(default=0)
room_name = models.CharField(max_length=20)
bed_name = models.CharField(max_length=20)
gender = models.IntegerField(default=0)
birth_date = models.DateField()
phone_number = models.CharField(max_length=11)
protector = models.CharField(default='protector',max_length=50)
def __str__(self):
return str(self.member_id)
def initIsUpdate(self):
self.is_update = 0
return 0
class Inpatient(models.Model):
member_id = models.ForeignKey(Member, on_delete=models.CASCADE, db_column = 'member_id', related_name='member')
inpatient_status = models.IntegerField(default=0)
is_in_room = models.IntegerField(default=0)
is_on_bed = models.IntegerField(default=0)
heart_rate = models.IntegerField(default=0)
breath_rate = models.IntegerField(default=0)
update_time = models.DateTimeField(auto_now_add=True, blank=True)
protector_name = models.CharField(max_length=50)
def __str__(self):
return str(self.member_id)
And Members are 4 people..
Each Members have same values in Inpatient DB.
It gets new queryset for every 1 sec.
And I want get 4 Member's most recent Inpatient DB.
How I get that DB??
class Inpatient(models.Model):
member_id = models.ForeignKey(Member, on_delete=models.CASCADE, db_column = 'member_id', related_name='member')
inpatient_status = models.IntegerField(default=0)
is_in_room = models.IntegerField(default=0)
is_on_bed = models.IntegerField(default=0)
heart_rate = models.IntegerField(default=0)
breath_rate = models.IntegerField(default=0)
update_time = models.DateTimeField(auto_now_add=True, blank=True)
protector_name = models.CharField(max_length=50)
class Meta:
get_latest_by = "update_time"
def __str__(self):
return str(self.member_id)
Now when you filter the members in views.py it will provide recent values..
I realize that the 3 models that I use right now have a ton of shared fields. I was wondering what the best way to condense these models would be. I've read some articles on metaclasses and model inheritance but wanted to see what the "best" way to do this would be.
models.py
class Car(models.Model):
created = models.DateTimeField(auto_now_add=True)
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField(default=2021, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)])
seats = models.PositiveSmallIntegerField()
color = models.CharField(max_length=100)
VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)])
current_mileage = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
class Truck(models.Model):
created = models.DateTimeField(auto_now_add=True)
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField(default=datetime.now().year, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)])
seats = models.PositiveSmallIntegerField()
bed_length = models.CharField(max_length=100)
color = models.CharField(max_length=100)
VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)])
current_mileage = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
class Boat(models.Model):
created = models.DateTimeField(auto_now_add=True)
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.PositiveSmallIntegerField(default=datetime.now().year, validators=[MaxValueValidator(datetime.now().year)])
length = models.CharField(max_length=100)
width = models.CharField(max_length=100)
HIN = models.CharField(max_length=14, validators=[MinLengthValidator(12)], blank=True)
current_hours = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
I can notice that some fields are similar but aren't the same, for example year are not the same for all. Due to that I propose to you the following.
class TimeStampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Vehicule(TimeStampedModel):
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
class Meta:
abstract = True
class WheeledVehicle(Vehicule):
seats = models.PositiveSmallIntegerField()
color = models.CharField(max_length=100)
VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)])
current_mileage = models.PositiveSmallIntegerField()
class Meta:
abstract = True
class Car(WheeledVehicle):
year = models.IntegerField(default=2021, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)])
class Truck(WheeledVehicle):
year = models.IntegerField(default=datetime.now().year, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)])
bed_length = models.CharField(max_length=100)
class Boat(Vehicule):
year = models.PositiveSmallIntegerField(default=datetime.now().year, validators=[MaxValueValidator(datetime.now().year)])
length = models.CharField(max_length=100)
width = models.CharField(max_length=100)
HIN = models.CharField(max_length=14, validators=[MinLengthValidator(12)], blank=True)
current_hours = models.PositiveSmallIntegerField()
And if you want to go further, I suggest you to add created_by and modified_by fields to audit.
class TimeStampedModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class TimeStampedAuthModel(TimeStampedModel):
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL,
related_name="%(app_label)s_%(class)s_created_by")
modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL,
related_name="%(app_label)s_%(class)s_modified_by")
class Meta:
abstract = True
class Vehicule(TimeStampedAuthModel):
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
class Meta:
abstract = True
class WheeledVehicle(Vehicule):
seats = models.PositiveSmallIntegerField()
color = models.CharField(max_length=100)
VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)])
current_mileage = models.PositiveSmallIntegerField()
class Meta:
abstract = True
class Car(WheeledVehicle):
year = models.IntegerField(default=2021, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)])
class Truck(WheeledVehicle):
year = models.IntegerField(default=datetime.now().year, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)])
bed_length = models.CharField(max_length=100)
class Boat(Vehicule):
year = models.PositiveSmallIntegerField(default=datetime.now().year, validators=[MaxValueValidator(datetime.now().year)])
length = models.CharField(max_length=100)
width = models.CharField(max_length=100)
HIN = models.CharField(max_length=14, validators=[MinLengthValidator(12)], blank=True)
current_hours = models.PositiveSmallIntegerField()
You can use model inheritance or model Mixins
model inheritance with abstract base model:
class AbstractVehicle(models.Model):
created = models.DateTimeField(auto_now_add=True)
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField(default=2021, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)])
class Meta:
abstract = True
class Car(AbstractVehicle):
seats = models.PositiveSmallIntegerField()
color = models.CharField(max_length=100)
VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)])
current_mileage = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
class Truck(AbstractVehicle):
seats = models.PositiveSmallIntegerField()
bed_length = models.CharField(max_length=100)
color = models.CharField(max_length=100)
VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)])
current_mileage = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
class Boat(AbstractVehicle):
length = models.CharField(max_length=100)
width = models.CharField(max_length=100)
HIN = models.CharField(max_length=14, validators=[MinLengthValidator(12)], blank=True)
current_hours = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
model mixins:
class VehicleMixin(object):
created = models.DateTimeField(auto_now_add=True)
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField(default=2021, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)])
class Car(VehicleMixin, models.Model):
seats = models.PositiveSmallIntegerField()
color = models.CharField(max_length=100)
VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)])
current_mileage = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
class Truck(VehicleMixin, models.Model):
seats = models.PositiveSmallIntegerField()
bed_length = models.CharField(max_length=100)
color = models.CharField(max_length=100)
VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)])
current_mileage = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
class Boat(VehicleMixin, models.Model):
length = models.CharField(max_length=100)
width = models.CharField(max_length=100)
HIN = models.CharField(max_length=14, validators=[MinLengthValidator(12)], blank=True)
current_hours = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
Both of these solutions will leave you with the same tables as your code. Also these are just simple examples. You may be able to improve them further. For Example you could add even more mixins or abstract base classes that contain the other fields.
You can combine the model by creating Vehicle and VehicleType in vehicle model you keep all common vehicle fields, in VehicleType keep the car, truck,boat etc with foreign-key reference to Vehicle model.
class VehicleType(models.Model):
name = models.CharField(max_length=100, unique=True)
created = models.DateTimeField(auto_now_add=True)
class Vehicle(models.Model):
vehicle_type = models.Foreinkey(VehicleType, on_delete=model.CASCADE)
created = models.DateTimeField(auto_now_add=True)
make = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField(default=datetime.now().year, validators=[MinValueValidator(1886), MaxValueValidator(datetime.now().year)])
seats = models.PositiveSmallIntegerField()
bed_length = models.CharField(max_length=100)
color = models.CharField(max_length=100)
VIN = models.CharField(max_length=17, validators=[MinLengthValidator(11)])
current_mileage = models.PositiveSmallIntegerField()
service_interval = models.CharField(max_length=50)
next_service = models.CharField(max_length=50)
If this question is stupid I'm sorry, but I couldn't really find anything useful on Google.
So I have a model made up of two fields.
I want to create a model with some other fields, but two of them should be the ones from the previous one. Is there any way to obtain this?
Code:
from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class CORMeserii(models.Model):
CodCOR = models.CharField(max_length=25, primary_key=True, unique=True)
MeserieCor = models.CharField(max_length=50, unique=True)
class Oferta(models.Model):
solicitant = models.ForeignKey(User, on_delete=models.CASCADE)
cor = models.ForeignKey(CORMeserii, max_length=25, on_delete=models.CASCADE)
meserie = models.ForeignKey(CORMeserii, max_length=50, to_field='MeserieCor', on_delete=models.CASCADE)
dataSolicitare = models.DateField(default=date.today)
denumireMeserie = models.CharField(max_length=50)
locuri = models.IntegerField()
agentEconomic = models.CharField(max_length=50)
adresa = models.CharField(max_length=150)
dataExpirare = models.DateField()
experientaSolicitata = models.CharField(max_length=200)
studiiSolicitate = models.CharField(max_length=200)
judet = models.CharField(max_length=20)
localitate = models.CharField(max_length=25)
telefon = models.CharField(max_length=12)
emailContact = models.EmailField(max_length=40)
rezolvata = models.BooleanField(default=False)
def __str__(self):
return self.cor
I thought this might work, but I get these errors:
from django.db import models
from django.contrib.auth.models import User
from datetime import date
from .validators import validate_file_size
# Create your models here.
class CORMeserii(models.Model):
CodCOR = models.CharField(max_length=25, primary_key=True, unique=True)
MeserieCor = models.CharField(max_length=50, unique=True)
class Oferta(models.Model):
solicitant = models.ForeignKey(User, on_delete=models.CASCADE)
cor = models.ForeignKey(CORMeserii, max_length=25, on_delete=models.CASCADE)
meserie = models.ForeignKey(CORMeserii, max_length=50, to_field='MeserieCor', on_delete=models.CASCADE)
dataSolicitare = models.DateField(default=date.today)
denumireMeserie = models.CharField(max_length=50)
locuri = models.IntegerField()
agentEconomic = models.CharField(max_length=50)
adresa = models.CharField(max_length=150)
dataExpirare = models.DateField()
experientaSolicitata = models.CharField(max_length=200)
studiiSolicitate = models.CharField(max_length=200)
judet = models.CharField(max_length=20)
localitate = models.CharField(max_length=25)
telefon = models.CharField(max_length=12)
emailContact = models.EmailField(max_length=40)
rezolvata = models.BooleanField(default=False)
def __str__(self):
return self.cor