Im new to django. I have this model, In tblperson, only the forgein keys of type and status are saved. How do I join all tables to display their value not their forgein key? For example.
TblPerson.objects.raw('SELECT * FROM "Tblperson" INNER JOIN "Tblstatus" ON ("TblPerson"."Status" = "Tblstatus"."ID")'):
Thanks.
class TblPerson(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'ID')
Type = models.IntegerField(null=True, db_column=u'Type', blank=True)
Status = models.IntegerField(null=True, db_column=u'Status', blank=True)
class Meta:
db_table = u'tblPerson'
class Tblstatus(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'statStatusID')
Status = models.CharField(max_length=25, db_column=u'statStatus', blank=True)
class Meta:
db_table = u'tblStatus'
class Tbltype(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'typTypeID')
Type = models.CharField(max_length=25, db_column=u'typType', blank=True)
class Meta:
db_table = u'tblType'
The power of Django is in the ORM, which means you should be writing very little SQL if at all.
class Person(models.Model):
#don't use this because id is generated automatically
#ID = models.AutoField(primary_key=True, db_column=u'ID')
type = models.ForeignKey(Type)
status = models.ForeignKey(Status)
#Type,Status analogous
#filter like this
selected = Person.objects.filter(type=SomeType)
for p in selected:
print p.id,p.type,p.status
I would suggest you to re-write your models. So, that your TblPerson has a many to one relationship with Tblstatus
class TblPerson(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'ID')
Type = models.IntegerField(null=True, db_column=u'Type', blank=True)
Status = models.ForeignKey(Tblstatus, null=True, db_column=u'Status', blank=True)
class Meta:
db_table = u'tblPerson'
class Tblstatus(models.Model):
ID = models.AutoField(primary_key=True, db_column=u'statStatusID')
Status = models.CharField(max_length=25, db_column=u'statStatus', blank=True)
class Meta:
db_table = u'tblStatus'
Using this you would be able to query for TblPerson objects for which Tblstatus exists like this
TblPerson.objects.filter(Status__isnull=False)
Related
I've setup a relationship using django's ForeignKey against 2 unmanaged tables like so:
class Product(BaseModel):
publish_name = models.CharField(unique=True, max_length=40)
# this works:
associated_country = models.ForeignKey('geonames.Countryinfo', models.DO_NOTHING, db_column='published_country', blank=True, null=True)
# this doesn't:
associated_continent = models.ForeignKey('geonames.Continentcodes', on_delete=models.DO_NOTHING, db_column='published_continent' blank=True, null=True)
class Meta:
managed = True
db_table = 'product'
class Continentcodes(models.Model):
code = models.CharField(max_length=2, primary_key=True, unique=True)
name = models.TextField(blank=True, null=True)
geoname_id = models.ForeignKey('Geoname', models.DO_NOTHING, blank=True, null=True, unique=True)
class Meta:
managed = False
db_table = 'geoname_continentcodes'
class Countryinfo(models.Model):
iso_alpha2 = models.CharField(primary_key=True, max_length=2)
country = models.TextField(blank=True, null=True)
geoname = models.ForeignKey('Geoname', models.DO_NOTHING, blank=True, null=True)
neighbours = models.TextField(blank=True, null=True)
class Meta:
ordering = ['country']
managed = False
db_table = 'geoname_countryinfo'
verbose_name_plural = 'Countries'
When I go to edit an entry in the django admin page for 'Products' I see this:
InvalidCursorName at /admin/product/6/change/ cursor
"_django_curs_140162796078848_sync_5" does not exist
The above exception (column geoname_continentcodes.geoname_id_id does
not exist LINE 1: ...ntcodes"."code", "geoname_continentcodes"."name",
"geoname_c...
^ HINT: Perhaps you meant to reference the column
"geoname_continentcodes.geoname_id"
It looks like it's trying to reference geoname_continentcodes.geoname_id_id for some reason. I have tried adding to='code' in the ForeignKey relationship, but it doesn't seem to effect anything.
Additionally, the associated_country relationship seems to work just fine if I comment out the associated_continent field. The associated_continent is the column that is giving some problem.
Here is some more context about what the table looks like in the database:
Removing the '_id' as the suffix is the fix. In this case geoname_id changed to geoname fixes this. Why? I have no idea. Django is doing something behind the scenes that is not clear to me. Here is the updated model:
class Continentcodes(models.Model):
code = models.CharField(max_length=2, primary_key=True, unique=True)
name = models.TextField(blank=True, null=True)
# remove '_id' as the suffix here
geoname = models.ForeignKey('Geoname', models.DO_NOTHING, blank=True, null=True, unique=True)
class Meta:
managed = False
db_table = 'geoname_continentcodes'
Django adds _id to the end to differentiate between the object and the id column in the table, geoname_id will return the table id where as geoname will return the object.
I want to be able to do queries involving multiple inner joins using Django ORM, here's my model (showing only relevant fields)
class Students(models.Model):
class Status(models.IntegerChoices):
preRegistered = 0 #No ha aceptado terminos y condiciones
Enabled = 1
Disabled = 2
Suspended = 3
Test = 4
id = models.AutoField(primary_key=True)
user = models.ForeignKey(Users, on_delete=models.CASCADE)
trainingPath = models.ForeignKey(trainingPaths, on_delete=models.CASCADE)
status = models.IntegerField(choices=Status.choices, default=0)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'Students'
class trainingPaths(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=70, blank=False, null=False)
shortName = models.CharField(max_length=10, blank=True)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'Training_Path'
class Courses(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=70, blank=False, null=False)
path = models.URLField(max_length=500, blank=True, null=True)
shortName = models.CharField(max_length=6, blank=True)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
course_image = models.URLField(max_length=200, blank=True)
class Meta():
db_table = 'Courses'
class CoursesXTrainingP(models.Model):
id = models.AutoField(primary_key=True)
trainingPath = models.ForeignKey(trainingPaths, on_delete=models.CASCADE)
course = models.ForeignKey(Courses, on_delete=models.CASCADE)
alternativeName = models.CharField(max_length=70, blank=True)
order = models.PositiveIntegerField(blank=False)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'Courses_X_Training_Paths'
I want to get the information of the courses that a student has according to the value of the "trainingPath".
this is my SQL query
select
courses.id, courses.`name`, courses.course_image
from
students
join
courses_x_training_paths
on
students.trainingPath_id = courses_x_training_paths.trainingPath_id
join
courses
on
courses_x_training_paths.course_id = courses.id
where
students.trainingPath_id=1;
I have tried several ways and none of them have worked, could you please help me?
You can filter with:
Courses.objects.filter(
coursesxtrainingp__trainingPath_id=1
)
The join on the Students model is not necessary, since we already know that the trainingPath_id is one by filtering on the CoursesXTrainingP model.
Note: normally a Django model is given a singular name, so Student instead of Students.
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: modification_date instead of modificationDate.
i'm trying to post a transaction via django rest framework, however it shows error in django log as below:
IntegrityError at /api/item_trans/
NOT NULL constraint failed: chemstore_itemtransaction.bin_code_id
it has no problem if I post the same data from the Django admin web.
therefore I suppose the problem has happened at DRF
any help is welcome, thank you
models.py
class BinLocation(models.Model):
bin_code = models.CharField(max_length=10, unique=True)
desc = models.CharField(max_length=50)
def __str__(self):
return self.bin_code
class Meta:
indexes = [models.Index(fields=['bin_code'])]
class ItemMaster(models.Model):
item_code = models.CharField(max_length=20, unique=True)
desc = models.CharField(max_length=50)
long_desc = models.CharField(max_length=150, blank=True)
helper_qty = models.DecimalField(max_digits=10, decimal_places=4)
unit = models.CharField(max_length=10, blank=False)
def __str__(self):
return self.item_code
class Meta:
verbose_name = "Item"
verbose_name_plural = "Items"
indexes = [models.Index(fields=['item_code'])]
class ItemTransaction(models.Model):
# trace_code YYMMDDXXXX where XXXX is random generated
trace_code = models.CharField(max_length=20, unique=False)
item_code = models.ForeignKey(
ItemMaster, on_delete=models.CASCADE, related_name='+', blank=False, null=False)
datetime = models.DateTimeField(auto_now=False, auto_now_add=False)
qty = models.DecimalField(max_digits=10, decimal_places=4)
unit = models.CharField(max_length=10, blank=False)
action = models.CharField(
max_length=1, choices=ACTION, blank=False, null=False)
bin_code = models.ForeignKey(
BinLocation, related_name='+', on_delete=models.CASCADE, blank=False, null=False)
remarks = models.TextField(blank=True)
def __str__(self):
return f"{self.trace_code} {self.datetime} {self.item_code} {dict(ACTION)[self.action]} {self.qty} {self.unit} {self.bin_code}"
serializers.py
class ItemMasterSerializer(serializers.ModelSerializer):
class Meta:
model = ItemMaster
fields = '__all__'
class ItemTransactionSerializer(serializers.ModelSerializer):
item_code = serializers.SlugRelatedField(
slug_field='item_code',
read_only=True
)
bin_code = serializers.SlugRelatedField(
slug_field='bin_code',
read_only=True,
allow_null=False
)
class Meta:
model = ItemTransaction
fields = '__all__'
You might need to use 2 fields, one for reading data and the other for creating and updating your data with its source to the main. In your case you could try this:
class ItemTransactionSerializer(serializers.ModelSerializer):
item_code_id = ItemMasterSerializer(read_only=True)
item_code = serializers.PrimaryKeyRelatedField(
queryset=ItemMaster.objects.all(),
write_only=True,
source='item_code_id'
)
bin_code_id = BinLocationSerializer(read_only=True
bin_code = serializers.PrimaryKeyRelatedField(
queryset= BinLocation.objects.all(),
write_only=True,
source='bin_code_id'
)
Since you have null=False in both of your ForeignKeys, DRF expects the corresponding ID. You seem to be getting the error NOT NULL constraint because you are not passing the ID in DRF. So you need to fix that for both bin_code_id and the item_code_id.
The query to be implemented with ORM is as follows,
SELECT t2.*
FROM sub_menu AS t1
INNER JOIN sub_menu AS t2 ON (t1.sub_menu_id = t2.parent_sub_menu_id)
WHERE t1.sub_menu_id = 1;
The model is as follows,
class SubMenu(models.Model):
sub_menu_id = models.AutoField(primary_key=True)
menu = models.ForeignKey('commons.MainMenu', related_name='sub_menus', on_delete=models.CASCADE)
parent_sub_menu_id = models.IntegerField(blank=True, null=True)
name = models.CharField(max_length=50)
en_name = models.CharField(max_length=50, blank=True)
ord = models.IntegerField()
api = models.CharField(max_length=255, blank=True)
api_method = models.CharField(max_length=7, blank=True)
api_detail = models.CharField(max_length=255, blank=True)
menu_type_cd = models.CharField(max_length=5, blank=True)
menu_auth_type_cd = models.CharField(max_length=5)
is_common = models.BooleanField(default=False)
is_ns = models.BooleanField(default=False)
spc_auth = models.BooleanField(default=False)
spc_auth_cd = models.CharField(max_length=5, blank=True)
create_dt = models.DateTimeField(auto_now_add=True)
update_dt = models.DateTimeField(auto_now=True)
class Meta:
db_table = 'sub_menu'
unique_together = ('api', 'api_method',)
Not using a raw method, Is it possible to implement with Django's ORM?
Thank you.
You should do the relationship correctly on your model: https://docs.djangoproject.com/en/3.0/ref/models/fields/#module-django.db.models.fields.related. Then the parent_sub_menu should be:
class Submenu:
parent_sub_menu = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)
Then run generate & DB migration. The query below should work.
And never declare relationship like you are doing right now, use Model instead via the documentation I sent.
Django does it for you already. You can just filter the related field.
https://docs.djangoproject.com/en/3.0/topics/db/queries/#lookups-that-span-relationships
SubMenu.objects.filter(parent_sub_menu__sub_menu_id=1)
I have been trying to use with the a legacy database. I have created models file using inscpectdb but now I am not able to perform joins on the table.
I have two tables job_info and username_userid.
Here is my models.class file:
class UseridUsername(models.Model):
userid = models.IntegerField(blank=True, null=True)
username = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'userid_username'
class LinuxJobTable(models.Model):
job_db_inx = models.AutoField(primary_key=True)
mod_time = models.IntegerField()
account = models.TextField(blank=True, null=True)
exit_code = models.IntegerField()
job_name = models.TextField()
id_job = models.IntegerField()
id_user = models.IntegerField()
class Meta:
managed = False
db_table = 'linux_job_table'
Heren is my serializable class :
class UseridUsernameSerializer(serializers.ModelSerializer):
class Meta:
model = UseridUsername
fields = ('userid','username')
class UserSerializer(serializers.ModelSerializer):
class Meta:
username = UseridUsernameSerializer(many=False)
model = LinuxJobTable
fields = ('account','mod_time','username')