Current Database Schema -
I have these 3 tables, Curriculum, Assignment, and Student. Every Student is assigned a Curriculum through a ForeginKey relationship between Student and Curriculum. Every
Assignment possesses the same relation with the Curriculum using a ForeginKey.
Problem Statement -
There are around 100 Assignments for each Curriculum, the problem is, some students need to be exempt from some assignments, so I want a way that I can exempt a Student from Assignments 1, 2, and 3 but have the rest of the students do the assignment 1, 2 and 3.
My solution that failed -
What I tried was, creating a ManyToManyField in Student table in relation to Assignment table. However, having to add hundreds of assignments manually would be ridiculously time-consuming for each student.
class Curriculum(models.Model):
name = models.CharField(max_length=50, null=False)
subject = models.CharField(max_length=30, choices=SUBJECT)
grade_level = models.CharField(max_length=20, choices=CURRICULUMGRADE, null=False)
tracking = models.CharField(max_length=20, choices=TRACKING, null=False)
required = models.CharField(max_length=20, null=True)
recorded_from = models.CharField(max_length=20, choices=RECORDED, null=False)
semesterend = models.CharField(max_length=50, null=True)
username = models.CharField(max_length=50, null=True)
password = models.CharField(max_length=50, null=True)
loginurl = models.CharField(max_length=100, null=True)
weight = models.IntegerField(null=True)
level = models.CharField(max_length=20, choices=LEVEL, null=False)
class Student(models.Model):
epicenter_id = models.CharField(
null=False, blank=False, unique=True, max_length=10
)
last_name = models.CharField(null=False, max_length=50)
first_name = models.CharField(null=False, max_length=50)
email = models.EmailField(null=False, max_length=120)
phone_number = models.CharField(null=False, max_length=50)
additional_email = models.EmailField(max_length=120, null=True)
additional_phone_number = models.CharField(max_length=20, null=True)
grade = models.CharField(max_length=20, choices=GRADELEVEL, null=False)
curriculum = models.ForeginKey('curriculum', null=True, blank=True, on_delete=models.SET_NULL)
class Assignment(models.Model):
standard = models.ManyToManyField(
Standard)
curriculum = models.ForeignKey(
Curriculum, on_delete=models.CASCADE, related_name="curriculum_assignment"
)
name = models.CharField(max_length=500, null=False)
description = models.CharField(max_length=500, null=False)
status = models.CharField(max_length=30, choices=STATUS, null=False)
type_of = models.CharField(max_length=30, choices=TYPE, null=False)
Alright, so the best solution I could think of was creating another table to store all the exempted assignments, called ExemptAssignements.
models.py
class ExemptAssignments(models.Model):
student = models.ForeginKey('student', null=True, blank=True, on_delete=models.SET_NULL)
assignments = models.ManyToMany('assignment', null=True, blank=True)
Now anytime I want to exempt the students from any Assignments, I can manually select them through the admin panel, as well the Student who's being exempted.
Now to get a list of all the assignments excluding the ones I have exempted I can simply use.
student = Student.objects.first()
Assignment.objects.filter(curriculum=student.curriculum).exclude(id__in=[x.id for x i in ExemptAssignment.objects.filter(student=student).assignment.all()]
And the above query will only show the Assignments which haven't been exempted.
Related
I can use some help on a query using 3 tables. Here is what my models contains.
class VolunteerRecord(models.Model):
eventname = models.CharField(help_text=_('Name of the event'),max_length=256, blank=False, default='')
category = models.CharField(max_length=256, blank=False, choices=CATEGORY_CHOICES)
hours = models.FloatField(blank=False)
date=models.DateField(help_text=_('Enter the date of the event'),validators=MaxValueValidator(limit_value=date.today)])
mileage = models.FloatField(blank=True, null=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
streetaddress1 = models.CharField(blank=True, max_length=256)
streetaddress2 = models.CharField(blank=True, max_length=256)
city = models.CharField(blank=True, max_length=30)
state = models.CharField(max_length=256, blank=False, choices=US_STATES)
zipcode = models.CharField(blank=True, max_length=15)
county = models.CharField(max_length=256, blank=False, choices=STATE_COUNTIES)
I would like to filter all VolunteerRecords where the owner's county = request.user's county
So far I have... (not sure what I am suppose to put where my ??? are)
def history(request):
current_user_county = request.user.profile.county
records = VolunteerRecord.objects.filter(????=current_user_county)
I was able to figure it our with your help.
records = VolunteerRecord.objects.filter(owner__profile__county=request.user.profile.county)
I want to manually delete records from sqlite table(witch was created with Django 1.10, Table from i want to delete records called main.storage_claim, it has relation to main.storage_claimlist), but got error: Error deleting record: no such table: main.storage_claimlist__old.
I dont know why it want this table.
I have only main.storage_claimlist without __old.
Btw, i`m using DB Browser for SQLite as gui tool for working with sqlite.
Can someone explain what the heck is __old?
ClaimList model:
class ClaimList(models.Model):
""" Claim list contains one to many claim. Used for grouping claims. """
created_at = models.DateTimeField(default=datetime.now, blank=True, null=True)
from_storage = models.ForeignKey(
Storage, related_name='from_storage', blank=True, null=True, default=True)
to_storage = models.ForeignKey(
Storage, related_name='to_storage', blank=True, null=True, default=True)
status = models.CharField(max_length=255, blank=True, null=True)
separation = models.CharField(max_length=255, blank=True, null=True)
insurance_company = models.ForeignKey(
InsuranceCompany, null=True, blank=True)
patient = models.CharField(max_length=255, blank=True, null=False)
Claim model:
class Claim(models.Model):
""" Claim contain information about what need to be transefer """
medicine = models.CharField(max_length=255, blank=True, null=True)
claim_list = models.ForeignKey(ClaimList, blank=True, null=True)
requested_amount = models.DecimalField(
default=0, max_digits=5, decimal_places=0)
given_amount = models.DecimalField(
default=0, max_digits=5, decimal_places=0)
requested_unit = models.CharField(max_length=100, blank=True, null=True)
given_unit = models.CharField(max_length=100, blank=True, null=True)
from_income = models.ForeignKey(Income, blank=True, null=True)
status = models.CharField(max_length=100, blank=True, null=True)
is_will_be_accepted_in_future = models.BooleanField(default=False)
price = models.DecimalField(null=True, max_digits=10, decimal_places=5)
sum = models.DecimalField(null=True, max_digits=10, decimal_places=5)
objects = ClaimManager()
I am new to Django and I need data from two models and would like to do it with one query. Here is what I have in sql that gives me exactly what I need. Can someone please show me how to do it in Django.
select api_userprofile.last_name, api_userprofile.first_name,
api_userdevice.is_admin,
api_userdevice.is_alerts_enabled,api_userdevice.is_owner from
api_userprofile
join api_userdevice on api_userdevice.user_id=api_userprofile.user_id
where api_userdevice.user_id=10 and api_userdevice.device_id=29
These are my 2 models:
class UserDevice(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False)
device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False)
activation_date = models.DateTimeField(default=timezone.now, null=False)
friendly_name = models.CharField(max_length=20, null=True, blank=True)
is_owner = models.BooleanField(null=False, default=False)
is_admin = models.BooleanField(null=False, default=True)
is_alerts_enabled = models.BooleanField(null=False, default=True)
class UserProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False)
token = models.TextField(null=False, blank=True)
first_name = models.TextField(null=True, blank=True)
last_name = models.TextField(null=True, blank=True)
Any help would be greatly appreciated.
There is easy way to do that:
User.objects.filter(userdevice__id=29, id=10).values('userdevice__is_owner', 'userdevice__is_admin', 'userdevice__is_alerts_enabled', 'userprofile__first_name', 'userprofile__last_name')
Customer.objects.filter(customer_id__in=contact_list_senders)
contact_list_senders is a repetitive QuerySet that involves some customer_ids:
{sender_id1, sender_id2, sender_id1, sender_id2, sender_id1}
When I try to find the Customer objects from the contact_list_senders QuerySet with the above code
Actual Output:
{Customer1, Customer2}
Desired Output
{Customer1, Customer2, Customer1, Customer2, Customer1}
I understand the actual output makes sense because there are only 2 Customer objects that matches with these contacts. Can you please help me to get the desired outcome?
models.py:
class Customer(models.Model):
customer_id = models.CharField(max_length=244, blank=False, null=False)
first_name = models.CharField(max_length=244, blank=True, null=True)
last_name = models.CharField(max_length=244, blank=True, null=True)
email = models.CharField(max_length=244, blank=False, null=False)
enrollment_method = models.CharField(max_length=244, blank=True, null=False)
account_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2)
reserved_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2)
modified = models.DateTimeField(auto_now_add=True)
created = models.DateTimeField(auto_now_add=True)
My understanding is that since Django 1.5, Custom User Models are possible but not neccesary. In fact, Greenfeld and Roy argue in "Two Scoops of Django" that sometimes (like for creating a third party package) "Profile" models are still the way to go.
Since getProfile() has been removed however, I don't know how to target my Profile data in template. Because:
{{ request.user.get_profile.id }}
no longer produces any data, I've tried:
{{ request.user.userprofile.id }}
but that doesn't produce a value either.
So my question is, given the following model:
class UserProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True, null=True, on_delete=models.SET_NULL)
fullname = models.CharField(max_length=64, unique=False)
company = models.ForeignKey(ClientList, blank=False, null=True, db_column='client', on_delete=models.SET_NULL)
position = models.CharField(max_length=64, unique=False, blank=True, null=True)
egroup = models.CharField(max_length=50, choices=EMP_GROUP_CHOICES)
address1 = models.CharField(max_length=130, unique=False, blank=True, null=True)
address2 = models.CharField(max_length=30, unique=False, blank=True, null=True)
city = models.CharField(max_length=64, unique=False, blank=True, null=True)
state = models.CharField(max_length=64, unique=False, blank=True, null=True)
zipcode = models.CharField(max_length=15, unique=False, blank=True, null=True)
phone = models.CharField(max_length=15, unique=False, blank=True, null=True)
extension = models.CharField(max_length=15, unique=False, blank=True, null=True)
hphone = models.CharField(max_length=15, unique=False, blank=True, null=True)
mobile = models.CharField(max_length=15, unique=False, blank=True, null=True)
fax = models.CharField(max_length=15, unique=False, blank=True, null=True)
notes = models.TextField(max_length=2000, blank=True, null=True)
email = models.EmailField()
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
def __str__(self):
return u'%s' % self.fullname
class Meta:
ordering = ['fullname']
class Admin:
pass
how do I get the userprofile.id in the template?
(note: not really relevant but the user object still explicity uses a foreign key in order to preserve the "on_delete" parameter)
To store user profile, it is recommended to use OneToOneField instead of ForeignKey with unique=True. Although they are the equivalent.
Once you set the relation to OneToOneField, you can retrieve the userprofile id by using the following query: user.userprofile.id
If you decide to use ForeignKey with unique=True, you can still retrieve it using the following queryset: user.userprofile_set.first()
Reference: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model