I want to have two models:
class Receipt(models.Model):
# Bunch of products
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField()
I don't want the product to know about receipt but just the receipt to know about the products. How do I build this relationship?
PS: One product can be in multiple receipts.
If it is just like you say a manyTomanyField is enough.
But if you need to store also the quantity of each ingredient on each receipe then do you need a many2many with attributes relation
One2Many relationship doesn't come out the box with Django. However, I think this answer is what you're after : Django one-to-many field without reversing dependency
Related
I am building an application where I need to add to the user model 'skills'. These skills are created and added by the user being this also a model.
I want to add to this skills, related with a many to many relationship, a value. This value will be a number from 1 to 10 specifing the level of the user at a particular skill.
So that I need to relate a level to each skill added to the user.
models.py
class Skill(models.Model):
name = models.CharField(max_length=50)
class Perfil(AbstractUser):
skills = models.ManyToManyField(Skill, blank=True, null=True)
Does anyone know how can I resolve this issue. Thanks in advance.
You can do this by adding the value to the many to many table. In order to be able to do this you would need to create a custom many to many table.
See the django documentation for an example.
I'm working on a mini project which uses Django 1.8. The aim is to build a small billing app. So, I've created two models, Bill and Product, as follows.
#bill/models.py
class Bill(models.Model):
date_of_issue = models.DateField()
name = models.CharField(max_length=50, default="N/A", null=True)
address = models.CharField(max_length=150, default="N/A", null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return "{} {}".format(self.input_name, self.date_of_issue)
class Product(models.Model):
bill = models.ForeignKey(Bill, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default="N/A")
quantity = models.IntegerField(default=0)
total = models.IntegerField(default=0)
By seeing the model, you can tell that my approach is to create Bill and Product tables and connect the Product to Bill via ForeignKey. Now, the thing is that a single bill will contain at least one product. If there are more than one product, how should I write my views in views.py. I'm a beginner in the Django development. If a Bill contains a single Product then I can write its view. But how can I store multiple Product which have different data and storing it in database.
For Example
The user will enter the name and address of the customer. Then the user will enter the details of products. Now I want to generate the Product modelform more than once (depends upon the number of products added by user). How can I accomplish this ?
Assuming
1) multiple products can be bought at once (and thus be part of one bill) and
2) one product can be bought multiple at any time (and thus be part of many bills)
a simple foreign key is the wrong modelling attempt. Instead of a m:1 relation you need a m:n relation - and thus a ManyToManyField. With a ManyToManyField you can add multiple products to one bill or have mutiple products added to multiple bills. In django-admin it's useful (and I recommend it) to put ManyToManyFields as filter_horizontal which eases the use of this field.
Plus, django will automatically resolve your m:n relation with an additional third database table, so you don't need to take care of this.
I'm building a project in which I'll have 3 types of users.
Super Admin
Teacher
Student
Teacher and Student will be in a table called Class, each Class will have one teacher and several Student.
As far as I know(Very limited), Django only provide one user table for all kinds of users, But I don't know how to go on, because I will need separated tables to keep the data organized and without redudance, in addition to relate with other tables.
Is there any kind of solution to solve this problem ?
You can implement related_name attributes something similar to this:
from django.contrib.auth.models import User
class ClassRoom(models.Model):
# One classroom one teacher
teacher = models.ForeignKey(User, related_name="teacher")
# One classroom many students
student = models.ManytoManyField(User, blank=True, null=True,
related_name="students")
.....
Also refer to these links for more info:
Django teacher students easy solution. Use separate tables, or permissions and groups? How? Other ideas?
Django model with Foreign Key and ManyToMany relations to same model
Two sets of users (teacher and student) in Django authentication
I have a model called Student that has a manytomany relationship with a model called Courses. I have another model called Attend in which I want to get all the courses the student is taking and pass it in as a select menu containing the courses the student is taking. I tried to get the id using the foreign key "student" and then get courses belonging to that student and put it in a list and pass it to choices but it didn't work obviously. I would like to know how I can get the courses belonging to the student to appear in the select menu.
Here is my model.
class Attend(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, default="")
time_signed_in = models.DateTimeField(auto_now_add=True)
isSignedIn = models.BooleanField(default=False)
# Below does not work, I get an error 'ForeignKey' object has no attribute 'id'
#courses = User.objects.get(id=student.id).courses
course = models.ForeignKey(Course, on_delete=models.CASCADE)
To render the courses the student is taking you should try using django forms.
If I understand correctly, you want a form that uses ModelMultipleChoiceField:
Allows the selection of one or more model objects, suitable for
representing a many-to-many relation.
class AttendForm(forms.Form):
courses = forms.ModelMultipleChoiceField(queryset=Courses.objects.filter(student__id=id))
That exapmple would only work to show the data to the user and then retrieving its choice. There is a slightly different approach to this case and that is using a ModelForm.
Every ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form.
ModelForm is a "database driven" form in which you can perform many task involving calls to the database easily.
Note: The queryset I used in the example is just an example, you dont have to use it that way.
I intend to create an app for categories which will have separate category sets (vocabularies) for pages, gallery, product types etc. So there will need to be two models, vocabulary and category.
The categories/models.py code might be something like this:
class Vocabulary(models.Model):
title = models.CharField()
class Category(models.Model):
title = models.CharField()
vocabulary = models.ForeignKey(Vocabulary)
From my pages, blogs, gallery, etc apps how I will need a ForeignKey field to categories:
class Page(models.Model):
title = models.CharField()
content = models.TextField()
category = models.ForeignKey('categories.Category')
This will of course list all available categories in the admin app. If I have a product I want only the product categories to be avaialble. How can I filter the available categories to a specific vocabulary?
I'm learning Django and not really sure where to begin. Maybe I have the whole model wrong? If there are any apps which already do it please let me know.
Filtering of selection like this is done in the form using a queryset, or in the admin interface with limit_choices_to.