Why do we use an intermediate model?
Can't we just use Many to many relationship without intermediate model?
M2M relationships require intermediate tables. You can read more about what M2M relationships are and why they require an intermediate table (referred to as a junction table in the article) here:
Django abstracts this away by automagically creating this intermediate table for you, unless you need to add custom fields on it. If you do, then you can define it by overriding the through parameter as shown here
Here's a quick picture of why the table is required
Source: https://www.geeksforgeeks.org/intermediate-fields-in-django-python/
Let's say you have two models which have a Many-to-Many relationship, like Customer and Product. One customer can buy many products and a product can be bought by many customers.
But you can have some data that doesn't belong to neither of them, but are important to the transaction, like: quantity or date.
Quantity and date are the intermediary data which are stored in intermediary models.
from django.db import models
class Item(models.Model):
name = models.CharField(max_length = 128)
price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __str__(self):
return self.name
class Customer(models.Model):
name = models.CharField(max_length = 128)
age = models.IntegerField()
items_purchased = models.ManyToManyField(Item, through = 'Purchase')
def __str__(self):
return self.name
class Purchase(models.Model):
item = models.ForeignKey(Item, on_delete = models.CASCADE)
customer = models.ForeignKey(Customer, on_delete = models.CASCADE)
date_purchased = models.DateField()
quantity_purchased = models.IntegerField()
When you buy a product, you do it through the Purchase model: the client customer buys quantity_purchased quantity of items item in date_purchased.
The Purchase model is the Intermediate model.
Django documentation says:
...if you want to manually specify the intermediary table, you can use
the through option to specify the Django model that represents the
intermediate table that you want to use.
In this case we have this line in the Customer model, which defines the intermediary model in through = 'Purchase'
items_purchased = models.ManyToManyField(Item, through = 'Purchase')
Let's now use the example from the Django Documentation.
You have a database of musicians with a Many-to-Many relationship with the bands the belong to: a musician can belong can be part of many bands, and the bands can have many musicians.
What data do you want to keep?
For musicians (person): name and instrument they play
For the bands: name and style.
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
age = models.IntegerField()
class Group(models.Model):
name = models.CharField(max_length=128)
style = models.CharField(max_length=128)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
But, wouldn't you think that knowing when the person joined the band is important? What model would be the natural place to add a date_joined field? It makes no sense to add it to Person or Group, because it's not an intrinsic field for each of them, but it's related to an action: joining the band.
So you make a small, but important adjustment. You create an intermediate model that will relate the Person, the Group with the Membership status (which includes the date_joined).
The new version is like this:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
age = models.IntegerField()
class Group(models.Model):
name = models.CharField(max_length=128)
style = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
The changes are:
You added a new class called Membership which reflects the membership status.
In the Group model you added members = models.ManyToManyField(Person, through='Membership'). With this you relate Person and Group with Membership, thanks to through.
Something important to clarify.
An intermediate model, or in relational database terms, an associative entity, are always needed in a Many-to-Many (M2M) relationship.
A relational database requires the implementation of a base relation
(or base table) to resolve many-to-many relationships. A base relation
representing this kind of entity is called, informally, an associative
table... that can contain references to columns from the same or different database tables within the same database.
An associative (or junction) table maps two or more tables together by
referencing the primary keys of each data table. In effect, it
contains a number of foreign keys, each in a many-to-one relationship
from the junction table to the individual data tables. The PK of the
associative table is typically composed of the FK columns themselves. (source)
Django will create the intermediate model, even when you don't explicitly define it with through.
Behind the scenes, Django creates an intermediary join table to
represent the many-to-many relationship. By default, this table name
is generated using the name of the many-to-many field and the name of
the table for the model that contains it.
Django will automatically generate a table to manage many-to-many
relationships. However, if you want to manually specify the
intermediary table, you can use the through option to specify the
Django model that represents the intermediate table that you want to
use.
The most common use for this option is when you want to associate extra data with a many-to-many relationship.(source)
Related
I have a many-2-many relationship between Flight and Passenger. When I try to assign a passenger to a flight object, Django seems to add an extra entry to the intermediate table.
Here are the models:
class Passenger(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
class Flight(models.Model):
time = models.DateTimeField('flight time')
destination = models.CharField(max_length=20)
passengers = models.ManyToManyField(
to=Passenger,
symmetrical=True,
related_name='flights',
blank=True,
)
Say the intermediate table looks like this, with passenger
Say flight_object is a Flight with ID=1, and passenger_object is a Passenger with ID=2, when I run flight_object.passengers.add(passenger_object) Django adds 2 entries to the intermediate table in the database. The table now looks like this:
Both entries with ID=1 and 2 should be there, but 3 is incorrect, and the flight_id foreign key is for a completely different flight!
That's because of symmetrical=True. You shouldn't create symmetrical ManyToMany relation to any model other than self.
According to docs, when using symmetrical=True, Django tries to insert the symmetrical record in the through table.
I'm working on a Django project, where I have amongst others, two models that have a relationship.
The first model describes a dish in general. It has a name and some other basic information, for instance:
dish(models.Model):
name = models.CharField(max_length=100)
short_desc = models.CharField(max_lenght=255)
vegetarian = models.BooleanField(default=False)
vegan = models.BooleanField(default=False)
The second model is related to the dish, I assume in form of a one-to-one relationship. This model contains the preparation and the ingredients. This data may change over time for the dish (e.g. preparation text is adjusted). Old versions of this text are still stored, but not connected to the dish. So the dish gets a new field, which points to the current preparation text.
preparation = models.???(???)
So, whenever the preparation description is changed a new entry is created for the preparation and the dish's reference to the preparation is updated.
The preparation itself looks like this:
preparation(models.Model):
prep_test = models.TextField()
ingredients = models.TextField()
last_update = models.DateTimeField()
As stated before, I believe that a one-to-one relation would be reasonable between the dish and the preparation.
Is my assumption with the one-to-one relation correct and if so, how do I correctly define it?
If you have multiple preparations for the dish, you don't have a one-to-one relationship by definition.
The way to define this is a ForeignKey from Preparation to Dish. (Note, Python style is that classes start with an upper case letter.)
class Preparation(models.Model):
...
dish = models.ForeignKey('Dish')
Now you can do my_dish.preparation_set.latest('last_update') to get the latest preparation for a dish. If you add an inner Meta class to Preparation and define get_latest_by = 'last_update'), you can leave out the parameter to the latest() call.
Make sure, relations are correct otherwise you have repeating tuples in your models which is not very good practice, make your database very heavy. see relation from my perspective.
class dish(models.Model):
name = models.CharField(max_length=100)
short_desc = models.CharField(max_lenght=255)
vegetarian = models.BooleanField(default=False)
vegan = models.BooleanField(default=False)
class Ingredients(models.Model):
name = models.CharField(max_length=100)
dish = models.ForeignKey(dish)
class preparation(models.Model):
prep_test = models.TextField()
last_update = models.DateTimeField()
dish = models.OneToOneField(dish)
why you don't make one2many relation of dish with preparation.
I dish have multiple preparation but have only one active. you can attach latest on base of last_update = models.DateTimeField()
your model will be like:
class preparation(models.Model):
dish = models.ForeignKey(dish)
...
I have the following Django model to store sparse product data in a relational database. I apologize myself for any wrong relationship in the code below (ForeignKey and/or ManyToMany might be wrongly placed, I am just playing around with Django for now).
class ProdCategory(models.Model):
category = models.CharField(max_length=32, primary_key=True)
class ProdFields(models.Model):
categoryid = models.ForeignKey(ProdCategory)
field = models.CharField(max_length=32)
class Product(models.Model):
name = models.CharField(max_length=20)
stock = models.IntegerField()
price = models.FloatField()
class ProdData(models.Model):
prodid = models.ManyToManyField(Product)
fieldid = models.ManyToManyField(ProdFields)
value = models.CharField(max_length=128)
The idea is to store the name, stock and price for each product in one table and the information for each product in the (id, value) format in another table.
I do know, a priori, the fields that each product category should have. For instance, a product of type Desktop should have, among others, memory size and storage size as fields, whereas another product of category Monitor should have resolution and screen size as fields.
My question is: How do I guarantee, in Django, that each product contains only the fields for its category? More precisely, when specifying a product of category Monitor, how to assure that only resolution and screen size are fields in the ProdData table?
I found a similar question Django: Advice on designing a model with varying fields, but there was no answer on how to assure the above.
Thank you in advance.
Django is an excellent framework, but it is still just an abstraction over a relation database.
What you are asking isn't efficiently possible in a relational database, so it will be tough to do in Django. Primarily, because at some point your code will need to be converted to tables.
There are basically 2 ways you can do this:
A product class with a ManyToMany relation to an attribute table:
class Product(models.Model):
name = models.CharField(max_length=20)
stock = models.IntegerField()
price = models.FloatField()
product_type = models.CharField(max_length=20) eg. Monitor, desktop, etc...
attributes = models.ManyToManyField(ProductAttribute)
class ProductAttribute(models.Model):
property = models.CharField(max_length=20) # eg. "resolution"
value = models.CharField(max_length=20) # eg. "1080p"
But, your logic around certain classes of objects having certain properties will be lost.
Use inheritance. Django is just Python, and inheritance is certainly possible - in fact its encouraged:
class Product(models.Model):
name = models.CharField(max_length=20)
stock = models.IntegerField()
price = models.FloatField()
class Desktop(Product):
memory_size = models.CharField(max_length=20)
storage_size = models.CharField(max_length=20)
class Monitor(Product):
resolution = models.CharField(max_length=20)
screen_size = models.CharField(max_length=20)
Then you can do queries on all products - Products.objects.all() - or just Monitors - Monitor.objects.all()` - and so on. This hard codes the possible products in code, so a new product type requires a database migration, but it also gives you the ability to embed your business logic in the models themselves.
There are trade-offs to both these approaches which you need to decide, so picking is up to you.
I have an entity in my application which has some attribute like auth.User but it has also some extra attributes. So I created a OneToOne relationship with auth.User
class UserEntity(models.Model):
user = models.OneToOneField(User)
... other fields ...
I also have a Person model which is UserEntity so created it as this:
class Person (models.Model):
userEntity = models.OneToOneField(UserEntity)
... other fields ...
There are many different attributes like addresses,experiences,education and other details that I want to associate with my Person. A Person can have many addresses,experiences,education,speciality
I have a Speciality Model like this.
class Speciality(models.Model):
name = models.CharField()
code = models.CharField()
... other fields ...
The problem is how should I my data model be designed so that I can retrieve a person/user with all addresses,expereiences,specialities etc. I can associate each Person/user with Speciality since Speciality is an independent model and can exist without a user. Currently I have created another model for each e.g for Speciality I have created
class PersonSpeciality(models.Model):
person = models.ForeignKey(Person)
specialities = models.ForeignKey(Speciality)
Can I design it in a better way so I can have fast searching and retrievals and no mess.
Thank you
If a Person can have multiple Specialities, then you can implement a oneToMany relationship, just by adding a foreignKey:
class Speciality(models.Model):
name = models.CharField()
code = models.CharField()
person = models.ForeignKey(Person)
However, if you have several Persons with the same specialities (let's say 10 Persons are Painters), you would have 10 different Painters entries.
To avoid duplication, you can implement a ManyToMany relationship :
class Speciality(models.Model):
name = models.CharField()
code = models.CharField()
person = models.ManyToManyField(Person)
Django will create a third table in your DB to handle that (you don't need to write your PersonSpeciality class).
I am reasonably new to Django and I want to achieve the following: I have a relationship between two tables, say table B has a ManyToMany reference to table A. Now I want a table called Options which saves options to a specific combination between A & B. How do I achieve this?
Thanks!
Hidde
Use the through option of the ManyToMany Field, and add the information in the relationship itself.
For example
class Ingredient(models.Model):
name = models.TextField()
class Recipe(models.Model):
name = models.TextField()
ingredients = models.ManyToManyField(Ingredient, through='RecipePart')
class RecipePart(models.Model)
recipe = models.ForeignKey(Recipe)
ingredient = models.ForeignKey(Ingredient)
amount = models.IntegerField()
# ...
RecipePart(recipe=pizza, ingredient=cheese, amount=9001).save()
If the relationship already exists (and you already have data) you will have to update the database schema (and create the model if you used to automatic mapping). South can help you do this.