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.")
Related
I have this model that records data in slug. The user has a relation with the award model. What am trying to do is list all login user's awards slug field data in the contain filter so i can use it to filter user's data.
NOTE : All the data in save in the SuccessfulTransactionHistory model field award is in slug format and SuccessfulTransactionHistory model has no foreign key relation to award and user
models.py
class Award(models.Model):
admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
image = models.ImageField(upload_to='award_images')
slug = models.SlugField(max_length=150, blank=True, null=True)
about_the_award = models.TextField(blank=True, null=True)
status = models.CharField(max_length=20, choices=STATUS_PUBLISHED, default='Closed')
price = models.DecimalField(max_digits=3, default='0.5', decimal_places=1, blank=True, null=True, validators = [MinValueValidator(0.1)])
bulk_voting = models.CharField(max_length=20, choices=BULK_VOTING, default='Closed')
amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2, blank=True,)
results_status = models.CharField(max_length=20, choices=RESULTS_PUBLISHED, default='private')
starting_date = models.DateTimeField()
ending_date = models.DateTimeField()
date = models.DateTimeField(auto_now_add=True)
class SuccessfulTransactionHistory(models.Model):
nominee_name = models.CharField(max_length=120)
transaction_id = models.CharField(max_length=120)
award = models.CharField(max_length=120)
amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2)
status = models.CharField(max_length=120, null=True, blank=True)
phone = models.CharField(max_length=120, null=True, blank=True)
date = models.DateTimeField(auto_now_add=True)
In my view.py
success_list = SuccessfulTransactionHistory.objects.filter(award__contains=request.user.award.slug).order_by('-date')
This is my error
'User' object has no attribute 'award'
``
Your User object has a lot of awards, because you use ForeignKey.
The relation is: One award has one User, but One user has one or more than one awards (award_set is the property name).
Solutions? Yes, of course,but depends on the context.
1- If the user has only one award, you can use OneToOneField, and your logic is ok.
2- If the user can have more than one Award, may be you need 2 steps.
Step 1: get all award slugs:
award_slugs = list(request.user.award_set.values_list('slug', flat=True))
where award_slugs is a list of slugs.
Step 2: Get success_list:
success_list = SuccessfulTransactionHistory.objects.filter(award__in=award_slugs)
I have Sport object which has many Source objects which in turn has many Feed objects. Each Feed object has a published time.
class Sport(Base):
name = models.CharField(max_length=255, unique=True)
class Source(Base):
name = models.CharField(db_index=True, max_length=255)
sport = models.ForeignKey(Sport, on_delete=models.CASCADE, null=True)
class Feed(Base):
title = models.CharField(db_index=True, max_length=255)
link = models.CharField(db_index=True, max_length=255, unique=True)
summary = models.TextField()
published = models.DateTimeField()
source = models.ForeignKey(Source, on_delete=models.CASCADE, null=True)
If I want to get all Feeds in the reverse chronology of published time where source has sport A, 20 at a time. I'm not sure how to do this with django ORM. Can someone help me with this query.
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)
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
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 !