Lookup between 2 related models in django form - python

I have 2 models: Company and Contact. Relation is one to many. I want to create a form in the way that in the beginning, the selectbox "company" is fullfilled with all data from database and selectbox "contact" is empty. Every time the selectbox "company" chooses a new company, the selectbox "contact" fullfills automatically with the contacts of the current company. I'm using django 1.4.
class Company(models.Model):
company_type = models.ForeignKey('CompanyType', on_delete=models.PROTECT)
name = models.CharField(max_length=50, default='')
description = models.CharField(max_length=100, default='', blank=True, null=True)
city = models.CharField(max_length=30, default='', blank=True)
telephone = models.CharField(max_length=20, default='', blank=True)
address = models.CharField(max_length=50, default='', blank=True)
postcode = models.CharField(max_length=10, default='', blank=True)
class Contact(models.Model):
company = models.ForeignKey('Company')
name = models.CharField(max_length=50, default='')
letterhead = models.CharField(max_length=50, default='',blank=True)
department = models.CharField(max_length=50, default='',blank=True)
telephone = models.CharField(max_length=20, default='',blank=True)
mobile_phone = models.CharField(max_length=20, default='',blank=True)
job = models.CharField(max_length=30, default='',blank=True)
email = models.CharField(max_length=50, default='',blank=True, validators=[validate_email])
fax = models.CharField(max_length=20, default='',blank=True)
active = models.BooleanField()
def __unicode__(self):
return self.name
Thanks in advance!!!

As #Daniel said, your best solution is Ajax, each time the user select a company, you get the select value, make an ajax request and insert the data in the forum. You have to use JS !

Related

Django many to many filter

I have many to many field in user model where one user can have multiple roles for example admin, patient, doctor and others. now I want to query data to get users with admin and all other roles and not doctor and patient role. I am using this
User.objects.exclude(roles__code_name__in=['pt', 'doc'])
now my one user signs up as patient too so he has admin and patient role both now i am unable to get him by using above query. so concluding... if user has two roles if one of it is patient and he has any other role too i want to get him too. what should i do? Thanks in advance
UPDATE
class User(AbstractBaseUser):
username = models.CharField(max_length=30, unique=True)
email = models.EmailField(max_length=60, blank=True, null=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
cnic = models.CharField(max_length=13, unique=True)
mobile = models.CharField(max_length=11, unique=True)
dob = models.DateField(blank=True, null=True)
full_name = models.CharField(max_length=90, blank=True, null=True)
profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_path, null=True, blank=True, default=get_default_profile_image_path)
next_of_kin_name = models.CharField(max_length=60, blank=True, null=True)
next_of_kin_mobile = models.CharField(max_length=11, blank=True, null=True)
is_delete = models.BooleanField(default=False)
status = models.IntegerField(default=0)
contact = models.CharField(max_length=10, blank=True, null=True)
hospital = models.ForeignKey('Hospital', on_delete=models.SET_NULL, blank=True, null=True)
roles = models.ManyToManyField('Role', related_name='users')
is_staff = models.BooleanField(default=False)
balance = models.PositiveIntegerField(default=0)
gender = models.CharField(max_length=10, choices=gender_choices, default=gender_choices[0][0])
phone_verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey('self', related_name='+', blank=True, null=True, on_delete=models.CASCADE)
updated_at = models.DateTimeField(auto_now=True)
updated_by = models.ForeignKey('self', related_name='+', blank=True, null=True, on_delete=models.CASCADE)
This is my model it has roles as many to many field. i have multiple roles like doctor, patient, admin and many others custom created roles with custom permissions. I have a view where i want to get data of users that are not patients or doctors. everything was working fine until one of my admin user decides to sign up as patient so he has now both patient and admin role and now i am unable to get him by using above mentioned query
Eureka. This solution is working fine for me idk if it's the ideal approach bit is working at the moment. Thanks #all
User.objects.annotate(num_roles=Count('roles')).exclude(Q(id=self.request.user.id) | Q(is_delete=True) | Q(roles__code_name__in=['pt', 'doc', 'su']) & Q(num_roles=1)).order_by('-id')

Two dependent conditions in exclude DJANGO

I want to check whether the current user already has the same movie id in his personal list or not. If he has it then I want to exclude that movie from my trending list.
I want it to be something like this.
views.py
trending = list(Movies.objects.exclude(mid in mymovies WHERE uid = request.user.id))
models.py
class Movies(models.Model):
mid = models.CharField(max_length=255, primary_key=True)
title = models.CharField(max_length=255, null=True, blank=True)
rating = models.CharField(max_length=5, null=True, blank=True)
type = models.CharField(max_length=255, null=True, blank=True)
genre = models.CharField(max_length=255, null=True, blank=True)
rdate = models.CharField(max_length=255, null=True, blank=True)
language = models.CharField(max_length=255, null=True, blank=True)
cover = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
sequal = models.CharField(max_length=255, null=True, blank=True)
trailer = models.CharField(max_length=255, null=True, blank=True)
year = models.CharField(max_length=5, null=True, blank=True)
objects = models.Manager()
def __str__(self) -> str:
return self.title
class MyMovies(models.Model):
mid = models.ForeignKey(Movies, on_delete=CASCADE)
uid = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True)
watched = models.BooleanField()
date = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
You can .exclude(…) with:
trending = Movies.objects.exclude(mymovies__uid=request.user)
If you specified a related_query_name=… [Django-doc] or a related_name=… [Django-doc], then you need to use that to make a JOIN with your Movies model:
trending = Movies.objects.exclude(related_name_of_fk__uid=request.user)
Note: normally a Django model is given a singular name, so MyMovie instead of MyMovies.
Note: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be user, instead of uid.

referral by company's product specific and company specific

I am thinking of creating a referral and reward app where a user will list his/her company with the product they have. A company can use referral program by product specific or just in whole(could not name it properly). For example, I have listed my company called ABC Company and I have a product like smartphone, smart Tvs, Laptops. I would like to market for my company by just saying refer me to 10 people and get something in return(this is non-product specific) or I should be able to market my specific product let's say when user goes to the abc phone XI and there will be refer this phone and get the same phone in return if you refer to more than 50 or if more than 10 then 10% discount etc. This is just an example to demonstrate my project.
For now I created the model for Company, Product(with nested category), referral. But I have no idea on how should i be able to keep the referral based on above example like product specific or based on full company.
Here is what I have done
class Product(models.Model):
"""
product model
"""
name = models.CharField(max_length=100, blank=True)
company = models.ForeignKey(Company, blank=False, null=False, on_delete=models.CASCADE)
category = TreeForeignKey('Category', null=True, blank=True, db_index=True, on_delete=models.CASCADE)
image = models.FileField(upload_to='/company/', max_length=100, blank=True, null=True)
description = models.TextField(blank=True, null=True)
stocks = models.IntegerField(default=0, blank=True)
class Company(models.Model):
"""
company model
"""
name = models.CharField(max_length=150, blank=False, null=False)
domain = models.URLField(blank=False, null=False)
email = models.EmailField()
description = models.TextField(blank=True)
pan_number = models.CharField(max_length=100, blank=False, null=False)
industry = models.CharField(max_length=150, blank=False, null=False)
class Join(models.Model):
"""
Join Model
"""
email = models.EmailField()
friend = models.ForeignKey("self", related_name='referral', null=True, blank=True, on_delete=models.CASCADE)
ref_id = models.CharField(max_length=120, default='ABC', unique=True)
count_added = models.ForeignKey("self", null=True, related_name='count', blank=True, on_delete=models.CASCADE)
ip_address = models.CharField(max_length=120, default='ABC')
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return '{}'.format(self.email)

What's the best way to connect these two Django models

In a Django project I have a Companies model and am putting together a ClinicalTrials model (CT), both of which are stored in a SQlite3 database for now. My initial plan was to query the CT.gov API for a company_name when a user visits the company page and store the results in the CT model mapping the company's primary key from the Companies model to a Foreign Key in the CT model.
As I start working through it though, I've realized that a trial will have a lead and could have multiple Collaborators which would result in storing multiple copies of the same trial record. So, I want to write the trial record once once and then connect multiple companies to the record.
My problem arises when I try to connect the other companies to the trial, simple because the company names in the trail are not always an exact match in my Companies model (i.e. my Companies table has the company_name as "Pharma Company Inc." and the collaborator field is "Pharma Company").
Is it best to search the Companies model using regex? Is there a better solution?
Also, what's the best way to store multiple Foreign Keys in a model? Or is better to build a helper table? Not really sure here...
Update
Adding code for clarity
ClinicalTrial model in my clincialtrial App
class ClinicalTrials(models.Model):
pk = models.CharField(primary_key=True, max_length=50, blank=False, null=False)
involvement = models.CharField(max_length=100, blank=False)
current_trial_status = models.CharField(max_length=200, blank=True)
current_trial_status_date = models.DateField(null=True)
start_date = models.DateField(null=True)
start_date_type_code = models.CharField(max_length=200, blank=True)
completion_date = models.DateField(null=True)
completion_date_type_code = models.CharField(max_length=200, blank=True)
record_verification_date = models.CharField(max_length=200, blank=True)
brief_title = models.CharField(max_length=200, blank=True)
official_title = models.CharField(max_length=200, blank=True)
brief_summary = models.CharField(max_length=200, blank=True)
study_protocol_type = models.CharField(max_length=200, blank=True)
primary_purpose_code = models.CharField(max_length=200, blank=True)
lead_org = models.CharField(max_length=200, blank=True)
phase = models.CharField(max_length=200, blank=True)
minimum_target_accrual_number = models.CharField(max_length=200, blank=True)
number_of_arms = models.CharField(max_length=200, blank=True)
Company model in my dashboard App
class Company(models.Model):
stock_symbol = models.CharField(max_length=5, unique=False)
company_name = models.CharField(max_length=200)
address_1 = models.CharField(max_length=100, blank=True)
address_2 = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=25, blank=True)
state = models.CharField(max_length=2, blank=True)
zip_code = models.IntegerField(null=True)
country = models.CharField(max_length=25, blank=True)
Just adding the relevant part of your ClinicalTrials Model here:
class ClinicalTrials(models.Model):
...
lead_org = models.ForeignKey(Company)
...
collaborator = Models.ManyToManyField(Company)
...
Then if you want to fetch all the ClinicalTrial objects that "Pharma Company Inc." is lead of, you just have to write the below filter
ClinicalTrials.objects.filter(lead_org__name="Pharma Company Inc.")
And if you want to fetch all the ClinicalTrial objects that "Pharma Company Inc." is a collaborator of, you can write:
ClinicalTrials.objects.filter(collaborator__name="Pharma Company Inc.")

show forms for model who can have multiple instance

I am creating a simple project which is about creating a resume by user. In resume, a user can have multiple experience, educational background and etc. That is why I have created the following table where experience, educational background, skills are foreignkey to the resume table.
class Resume(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100, blank=False, null=False, help_text="Full Name")
slug = models.SlugField(max_length=50, unique=True)
designation = models.CharField(max_length=200, blank=True, null=True)
city = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.name
class Education(models.Model):
resume = models.ForeignKey(Resume, related_name='education')
name = models.CharField(max_length=100, blank=False, null=False, help_text="Name of an institution")
course = models.CharField(max_length=200, blank=False, null=False, help_text="Name of a course")
description = models.CharField(max_length=400, blank=True, null=True)
start_date = models.DateField()
end_date = models.DateField()
class Experience(models.Model):
resume = models.ForeignKey(Resume, related_name='experience')
designation = models.CharField(max_length=100, blank=True, null=True)
company = models.CharField(max_length=100, blank=True, null=True)
description=models.CharField(max_length=400, blank=True, null=True)
start_date = models.DateField()
end_date = models.DateField()
class Skill(models.Model):
resume=models.ForeignKey(Resume, related_name="skills")
name = models.CharField(max_length=100, blank=True, null=True, help_text="Name of the skill")
class Meta:
verbose_name='Skill'
verbose_name_plural='Skills'
def __str__(self):
return self.name
Now for such situation, do I have to create a ResumeForm, EducationForm, ExperienceForm etc and create an Education, Experience and Skill formset or
I have to do something else. I do not have clear idea on how to move forward now for developing form with such
relation where Education, Skill can have multiple instance. Can anyone guide me, please?
Well the question is unclear but following with your idea you have 2 options:
First you can have existing values in Education, Experience, Skill. Then in the view you have a checkbox to add education, experience, skill.
Second you can add education, experience, skill creating a modelForm for each one and then passing the resume, It is not necessary use formset here

Categories