Django- manytomany model relationships - django

I'm still learning about how to setup up relational databases. I'm trying to create a db that tracks universities, departments, and their programs. My question is a relationship one. Each university might have one or more departments. This relationship should then be a many to many. Each department may have one or more programs, so I can see the relationship between the department and the programs being many to many.
The problem that I have is if I want to have a department that belongs to a university, I feel like I should use an intermediary to attach a program to that department. But then, if I want to add another program to the same department, I would end up having two of the same departments belonging to the one university. This doesn't seem right.
In other words:
class Department(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
def __unicode__(self):
return '{}'.format(self.description)
class Universities(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
departments = models.ManyToManyField(Department,through='UniversityHasDepartment')
class Program(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
def __unicode__(self):
return '{}'.format(self.description)
class UniversityHasDepartment(models.Model):
university = models.ForeignKey(Universities)
department = models.ForeignKey(Department)
program = models.ForeignKey(Program)

I think you want to use foreign keys. (one to many relationships).
Each university can have multiple departments but a department can only have 1 university.
Each department can have multiple programs but a program can only have 1 department.
class University(models.Model):
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
class Department(models.Model):
university = models.ForeignKey(University, related_name='departments')
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
class Program(models.Model):
department = models.ForeignKey(Department, related_name='programs')
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)

Related

Merge Django models into a view

I am attempting to merge and pull data from three Django models into a view. Players and Events relate to each other in the Details model (a player can attend many events) using models.ForeignKey.
In other platforms I would have written a DB View to join tables and the application would query that view.
From what I understand Django does not support data views within Models.
Looking for help on how I would approach this in Django.
class Players(models.Model):
firstName = models.CharField(max_length=255)
lastName = models.CharField(max_length=255)
highSchool = models.CharField(max_length=255)
gradYear = models.IntegerField()
slug = models.SlugField(default="", null=False)
class Events(models.Model):
title = models.CharField(max_length=255)
location = models.CharField(max_length=255)
date = models.DateField()
class Details(models.Model):
event = models.ForeignKey(Events, on_delete=models.CASCADE)
player = models.ForeignKey(Players, on_delete=models.CASCADE)
height = models.IntegerField(default=None, blank=True)
weight = models.IntegerField(default=None, blank=True)
def playerdetail(request,slug):
playerinfo = Details.objects.get(id=1)
template = loader.get_template('playerdetail.html')
context = {
'playerinfo': playerinfo,
}
return HttpResponse(template.render(context, request))
You are actually doing what you needed to do with the code you provided.
When you are invoking a query on a model that connects those two entities (Players,Events), it performs the join when you try to access each of these properties through the foreign key fields.
For example, for accessing the player information (which makes the Django ORM perform the join operation in the background):
# Get the first name of the player
first_name = playerinfo.player.firstName
For filtering and showing in other places, you can use the notation field__subfield
For more information, please read the examples of this website:
https://books.agiliq.com/projects/django-orm-cookbook/en/latest/index.html

Django model using hashmap

I have a question about how to properly model my data in Django (and later in graphene).
I have a model exam which consists of date, subject, participants, results where subject,participants, results are references to other objects. I could of course have two lists of participants and results however it would be practical to have a map of type:
pseudocode:
results= map(participant,result)
To be honest I do not know if this is even possible without introducing a additional model object participant_results
Any insight very welcome.
Benedict
I would model it this way:
class Exam(models.Model):
date = models.DateField()
subject = models.TextField()
class Participant(models.Model):
person = models.ForeignKey(Person, on_delete=models.PROTECT, related_name="participants")
result = models.FloatField(null=True, blank=True)
exam = models.ForeignKey(Exam, on_delete=models.PROTECT)
class Person(models.Model):
name = ...
You retrieve all participant from an exam using
exam.participants

Making many-to-many relationships with different price for different customer

I have three models Product, Buyer and Offer.
Any buyer can inquire about any kind of Product but for each customer I might offer a different price.
The net price of a product is already given by the supplier.
I wrote the code below and suddenly realized I can only select products for an offersheet but cannot give a different price every time for each product and for each customer with this code.
It would be nice if anyone could give me some suggestions.
Thanks.
class Product(models.Model):
name = models.CharField(...)
net_price = models.NumericField(...)
class Buyer(models.Model):
name = models.CharField(...)
class Offer(models.Model):
date = models.DateTimeField(auto_created=True, auto_now_add=True)
buyer = models.ForeignKey(Buyer, default='',)
products = models.ManyToManyField(Product, related_name='offer',)
You can do it as following:
class Product(models.Model):
name = models.CharField(...)
class Buyer(models.Model):
name = models.CharField(...)
class Offer(models.Model):
date = models.DateTimeField(auto_created=True, auto_now_add=True)
buyer = models.ForeignKey(Buyer)
class OfferUnit(models.Model):
offer = models.ForeignKey(Offer)
product = models.ForeignKey(Product)
net_price = models.IntegerField()
OfferUnit is like one row in your bill(invoice) so you can specify different price for different buyers.

Which approach is better in Django Jsonfield or ForeignKey?

Such a question, I want to create a price comparison site, there are two ideas how to implement a list of prices from different stores.
First via ForeignKey
class Price(models.Model):
price = models.DecimalField()
shop = models.CharField()
class Product(models.Model):
name = models.CharField(max_length=255)
prices = models.ForeignKey()
JSONfield second method
class Product(models.Model):
name = models.CharField(max_length=255)
data = JSONField()
""" Product.objects.create(name='product', data={'price': 999,
'shop': 'Amazon.com'}
def __str__(self):
return self.name
If anyone has experience, what works faster and more reliable if a large number of goods? Thanks for the early ones.

Django models for school timetable?

I am building a school timetable app for each room? There are my models. Is there anything i am missing?
class Building(models.Model):
bid = models.CharField(max_length=10, primary_key=True)
name = models.CharField(max_length=255, unique=True)
class Meta:
ordering = ['bid']
def __str__(self):
return f'{self.bid}'
class Room(models.Model):
building = models.ForeignKey(Building, on_delete=models.CASCADE,
related_name='rooms')
number = models.PositiveIntegerField()
availability = models.BooleanField(default=False)
power = models.BooleanField(default=False)
class Meta:
ordering = ['building', 'number']
unique_together = ['building', 'number']
def __str__(self):
return f'{self.building.bid}/{self.number}'
class Occurrence(models.Model):
date = models.DateField('Date')
start_period = models.ForeignKey(Period, on_delete=models.CASCADE, related_name='start_at')
end_period = models.ForeignKey(Period, on_delete=models.CASCADE, related_name='end_at')
class Meta:
abstract = True
class Period(models.Model):
start = models.TimeField()
end = models.TimeField()
objects = PeriodManager()
class Meta:
ordering = ['start']
def __str__(self):
return f'{self.start}-{self.end}'
def check_time(self):
return True if self.start < self.end else False
def check_overlap(self):
pass
class TimetableModel(models.Model):
class Meta:
abstract =True
There will be a model name Booking which extends from Occurrence to allow students register to use a room in periods. I would like to make a Timetable model link to a Room Model for providing to context for rendering different weeks timetable for a room and Period models which are resemble school periods. Any advises?
I think you may need to re-think your actual models and what you're trying to achieve.
Having a look at your models you seemed to create models for different aspects of what you're trying to do but there doesn't seems to be coherence between the models.
For instance one way to look at it would be as follows:
Building
- Name
Room
- Number
- Building (FK)
Booking
- Room
- Period (you could just have statically defined list assume these are fixed)
- Duration (number of periods, this removes the need to specify end as you can calculate it.
To make a booking you need to know the following:
- The room you want to book
- The period you want to use it
- How long you'd like to book it for (ie. 2 periods)
From a data perspective that's probably the simplest models you can build (simple is always better). In terms of showing what is available you can do that at the point where you're making a booking (booking form).
I hope that gives you some idea of how to approach this, I didn't create models in this answer as I think your question wasn't really a technical how to but more of a point in the right direction.