Django - Sqlite Database - django

Any help is greatly appreciated.
I am using Django and SQLite, I am trying to join the auto generated auth_user table with an input table that I have created using a model.
Models.py;
class Input(models.Model):
height = models.IntegerField(default=0)
waist = models.IntegerField(default=0)
bust = models.IntegerField(default=0)
hips = models.IntegerField(default=0)
class Meta:
db_table = "Project_input"
The purpose of joining the tables is so that when a user logs in the information they enter into my input table is only associated with them.
I understand that I have to add a foreign key to this model! But how do I reference the auth_user table?

Just add a ForeignKey field to the model.
class Input(...):
user = models.ForeignKey('auth.User') # (or `settings.AUTH_USER_MODEL`)
# ...
See the Django docs about foreign keys and other many-to-one relations.

I think, All you need that to edit your model to this
Models.py
from django.contrib.auth.models import User
class Input(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='inpute')
height = models.IntegerField(default=0)
waist = models.IntegerField(default=0)
bust = models.IntegerField(default=0)
hips = models.IntegerField(default=0)
class Meta:
db_table = "Project_input"
With this, you make one to one relationship with the class user which Django provides.

Related

Django model order the queryset based on booleanfield True/False that related with User FK profile

I have two django models as follows:
The first one is a user profile, which has a FK to User model:
class Profile(models.Model):
PRF_user = models.OneToOneField(User, related_name='related_PRF_user', on_delete=models.CASCADE)
PRF_Priority_Support = models.BooleanField(default=False)
and the second is ticket model which has a FK to User model:
class ticket(models.Model):
ticket_status_options = [
('open', 'open'),
('wait_customer_reply', 'wait_customer_reply'),
('replied_by_staff', 'replied_by_staff'),
('replied_by_customer', 'replied_by_customer'),
('solved', 'solved'),
]
TKT_USER = models.ForeignKey(User, related_name='TKT_USER', on_delete=models.CASCADE)
TKT_DEB = models.ForeignKey('Site_departments', related_name='related_ticket_department', on_delete=models.CASCADE)
TKT_SUB = models.CharField(max_length=50, db_index=True, verbose_name="ticket subject")
TKT_BOD = models.TextField(verbose_name="ticket body")
TKT_image_attachment = models.ImageField(upload_to='TKT_img_attachment', blank=True, null=True , default=None)
TKT_CREATED_DATE = models.DateTimeField(auto_now_add=True)
TKT_UPDATED_DATE = models.DateTimeField(auto_now=True)
I want to sort the tickets based on user profile Priority_Support:
If the user profile PRF_Priority_Support is True, I want to sort it first inside my views QuerySet, otherwise (if PRF_Priority_Support is False) I want to sort it normally.
How can I do this?
You should name your model starting with a capital letter.
And for ordering the tickets, you can use something like this:
' queryset_list = ticket.objects.order_by('-TKT_USER__related_PRF_user__PRF_Priority_Support')
In filtering, when you want to span relationships, you use double underscore __ .
More on this here:
https://docs.djangoproject.com/en/3.1/topics/db/queries/#lookups-that-span-relationships
Another way is adding ordering to your model's Meta class.
For Example:
MyModel(models.Model):
class Meta:
ordering = ('-my_boolean_field ',)
Hi you should filter as follow:
Model.objects.filter(field=True) or False depending on what you need
Regards

How do I populate FOREIGN KEY with a Django form

I am trying to give the user the ability to enter data
here is my models named cv :
class Experience_Pro(models.Model):
annee_debut = models.IntegerField()
annee_fin = models.IntegerField()
description_exp_pro = models.TextField(null=True,blank=True)
class Ecole(models.Model):
nom_ecole = models.CharField(max_length=50)
classement = models.IntegerField()
class Academic(models.Model):
annee_debut = models.IntegerField()
annee_fin = models.IntegerField()
type_diplome = models.CharField(max_length=10)
description_academic = models.TextField(null=True,blank=True)
ecole = models.ForeignKey('Ecole' , on_delete=models.DO_NOTHING)
class Cv(models.Model):
experience_Pro = models.ForeignKey('Experience_Pro' ,on_delete=models.CASCADE)
academic = models.ForeignKey('Academic',on_delete=models.CASCADE)
and here is my form
class CvForm(forms.ModelForm):
class Meta:
model = Cv
fields = "__all__"
but instead of getting inputs for the user to enter data i get a dropdownlist of already existed records in my database.
Unfortunately, that is the way django is designed when using a ModelForm.
Realistically, you can create two model forms from the Experience & Academic models and join them in the view.
Multiple Models in a single django ModelForm?
Your cv model doesnt have any fields for input. You are only have the relation with other model as a foreignkey relation. This way you can only access the data here not create one

django admin list_display SQL joindata

The pages made of existing php are being changed to python and Django.
Existing Query
Select
l.lawyer_idx,
l.lawyer_email,
lp.lawyer_profile_path,
lp.lawyer_profile_name,
lc.lawyer_company_name,
lc.lawyer_company_address,
lc.lawyer_detail_address,
l.lawyer_agent
from lawyer l
left join lawyer_profile lp on l.lawyer_idx = lp.lawyer_idx
left join lawyer_company lc on l.lawyer_idx = lc.lawyer_idx
order by l.register_date desc;
I made each table at models.py
models.py
class Lawyer(models.Model):
lawyer_idx = models.AutoField('ID', primary_key=True)
lawyer_email = models.CharField('E-mail', unique=True, max_length=200)
lawyer_agent = models.CharField(max_length=1, blank=True, null=True)
class Meta:
managed = False
db_table = 'lawyer'
class LawyerProfile(models.Model):
lawyer_idx = models.AutoField('ID', primary_key=True)
lawyer_profile_path = models.CharField(max_length=200, blank=True, null=True)
lawyer_profile_name = models.CharField(max_length=100, blank=True, null=True)
.................
class LawyerCompany(models.Model):
lawyer_idx = models.AutoField('ID', primary_key=True)
lawyer_company_name = models.CharField(max_length=100)
...............
We would like to place the following query into the
list_display portion of Django Admin.py Is there any way to show the data that did join in sql?
Admin.py
from django.contrib import admin
from .models import Lawyer, LawyerCompany, LawyerProfile
#admin.register(Lawyer)
class LawyerAdmin(admin.ModelAdmin):
list_per_page = 100
**list_display = ['lawyer_idx', 'lawyer_email',
'lawyer_agent', 'lawyer_profile_path', 'lawyer_profile_name', 'lawyer_company_name']**
You could add the query as a raw sql query, but that wouldnt make much use of Django's ORM then.
You are not explicitly defining any relationships on your models, so Django doesn't know about how your models relate.
If lawyer_idx references the lawyer you could change the field to a OneToOneField/ForeignKey (an AutoField is probably the wrong choice here anyways, as the values should correspond to those in the Lawyer model and not be auto-generated). Also have a look at the documentation for one-to-one and many-to-one relationships.
class LawyerProfile(models.Model):
lawyer = models.OneToOneField(Lawyer, primary_key=True,
db_column="lawyer_idx", related_name="profile")
Django should perform the joins automatically when accessing the related data; on a Lawyer instance you can then access the profile via its related_name .profile. In the list_display option you can use the double underscore syntax to access related data:
list_display = ['lawyer_idx','lawyer_agent', 'profile__lawyer_profile_path']
list_select_related = ['profile']
If you add the list_select_related option Django will already join the specified table beforehand, so no additional queries are performed when accessing the related data.

django queryset between two tables without foreign key

I am trying to fetch results from two tables which does n't have a foreign key relation, Just want to know approach I'm using is right or not.
django.db import models
django.contrib.auth.user import User
class UserWorkExperience(models.Model):
user = models.ForeignKey(UserProfile)
job_title = models.CharField(max_length=255)
salary = models.IntegerField(null=True,default='0')
class UserSkills(models.Model):
user = models.ForeignKey(UserProfile)
skill_name = models.CharField(max_length=255)
So What I want is all records for
skills of all user which have job-title 'software engineer' and salary greater than '100000'
user_ids = UserWorkExperience.objects.filter(job_title='software engineer', salary__gt=100000).values_list('user', flat=True)
skills = UserSkills.objects.filter(user__in=user_ids)
It is recommended to use a ForeignKey for job_title and also skill_name

How to create custom relation table for ForeignKey or OnetoOne field?

What I want to do is create a model than can be used to store data about a relation between two elements. With ManytoMany fields, I can use the parameter "through" and specify a model which stores two elements foreign keys as below.
def MyModel(models.Model):
relation = models.ManyToManyField('AnotherModel', through='RelationModel')
def RelationModel(models.Model):
model1 = models.ForeignKey('MyModel')
model2 = models.ForeignKey('AnotherModel')
slug = models.CharField()
What would be the equivalent for a OnetoOne relation or a ForeignKey relation ? I've read the docs about custom managers and some posts on SO so in the end I'm quite confused and I dont know what is the solution. Thanks in advance for any help.
you can do like this
from products.models import VendorDetails
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE)
user_location = models.CharField(max_length=50, null=True)
vendor_category = models.ManyToManyField(VendorDetails, through="UserProfileVendorCategory")
class UserProfileVendorCategory(models.Model):
user_profile = models.ForeignKey(UserProfile)
vendor_category = models.ForeignKey(VendorDetails)
location = models.CharField(max_length=256)