Python Django - Accessing foreignkey data - python

I am trying to figure out how to get data from my models with ForeignKey relationships. I have the following models.py:
class wine(models.Model):
name = models.CharField(max_length=256)
year = models.CharField(max_length=4)
description = models.TextField()
class collection(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(null=True)
class collection_detail(models.Model):
collection = models.ForeignKey(collection)
wine = models.ForeignKey(wine)
quantity = models.IntegerField()
price_paid = models.DecimalField(max_digits=5, decimal_places=2)
value = models.DecimalField(max_digits=5, decimal_places=2)
bottle_size = models.ForeignKey(bottle_size)
Wine is a basic table, Collection Detail is a table that references a wine and adds user specific data (like price paid) to it. Collection is a group of collection_detail objects.
I am struggling on how to access data within these models. I can easily display data from a specific model, but when viewing a particular collection, I cannot access the collection_detail.wine.name data. Do I need to write specific queries to do this? Can I access this data from the templating language? My data model appears correct when viewed via the admin, I can add the data and relationships I need.
Thanks for any help!

Use collection_detail_set to obtain a queryset of all collection_detail's with that collection.
If you want a one-to-one relationship instead of a one-to-many (which is what you get using ForeignKey), change
collection = models.ForeignKey(collection)
to
collection = models.OneToOneField(collection)
and access the collection's collection_detail simply by calling collection_detail from your collection model.

Related

What's the use of Intermediate models in Django?

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)

Correctly defining this data relation in Django models

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)
...

Django: Model with varying fields (Entity-Attribute-Value model)

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.

Is it possible to use a PositiveIntegerField as a foreign key in Django?

Consider the following two Django models:
class Item(models.Model):
'''
Represents a single item.
'''
title = models.TextField()
class Information(models.Model):
'''
Stores information about an item.
'''
approved = models.BooleanField(default=False)
multipurpose_field = models.PositiveIntegerField()
Due to the way the models are organized, I am forced to use a PositiveIntegerField in Information for referencing an Item instead of using a ForeignKey. This makes queries more difficult.
I would like to select all items referenced by an Information instance with approved set to True. In other words, I would like to do this:
Information.objects.filter(approved=True)
...except that the query will return instances of Information instead of the Item referenced in multipurpose_field.
I probably could do this with raw SQL:
SELECT app_item.title FROM app_item
LEFT JOIN app_information
ON app_information.multipurpose_field = app_item.id
WHERE app_information.approved = 1
Is there a way to do this without resorting to raw SQL (which often isn't very portable)?
ForeignKey's field type is determined by the related field. Consider redesigning your models this way:
class Item(models.Model):
id = models.PositiveIntegerField(primary_key=True)
title = models.TextField()
class Information(models.Model):
approved = models.BooleanField(default=False)
multipurpose_field = models.ForeignKey(Item)
Then your query will be represented this way:
Item.objects.filter(information__approved=True)

How do I make a class a sub-group of another class?

from django.db import models
class products(models.Model): #Table name, has to wrap models.Model to get the functionality of Django.
name = models.CharField(max_length=200, unique=True) #Like a VARCHAR field
description = models.TextField() #Like a TEXT field
price = models.IntegerField()
def __unicode__(self): #Tell it to return as a unicode string (The name of the to-do item) rather than just Object.
return self.name
class categories(models.Model):
I'm a python newbie and I'm trying to create an e-commerce store. As you can see above, I've created the products class, but in the Categories class, I need to include all the products I create come under a certain category. I have no clue how to do this.
Sounds like you just want a ForeignKey from Product to Category.
Take a look at Many to Many
I think a Product can belong to Many categories so it should have a ManyToMany relationship to the Category model.

Categories

Resources