I'm trying to understand relationships on django and create a little project but I'm stuck.So basically I want to add a field (sort of basket) so that people can add their favourite items among many of them. But I can't implement it. What should I do inside my models? Thanks. Bye the way I want to turn this into RESTFUL.I'll appreciate if you give me any advice.
models.py
from django.db import models
from django.contrib.auth.models import User
class Products(models.Model):
name = models.CharField(max_length=20)
price = models.IntegerField()
fav_product = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.name
It should be ManytoMany relationship in my opinion. Product can has many users (many users can add the product to favourites) and user can has many products (user can add many products to favourites).
Related
I have a Netflix clone app that I am creating and I am having difficulty with the models.
I have a Movie model that has fields for the movie such as a title, duration, rating, etc.
I am not sure how I should model my database but what I believe I should be doing is a ManyToMany relationship, such as, a user can favorite many movies and a movie can be favorited by many users.
However, if I do it like this I feel that I would end up with a Favorites table that would have many users and movies and possible see this as an issue having to go through each row to find the current user rather than doing maybe a OneToMany relationship, such as, a user can favorite many movies and a movie can be favorited by a user.
So first, I am not sure what the proper way of modeling this would be.
I also do not know how to add this relationship to my user model because I am using the User model that I brought in from django.contrib.auth.models
I am having a lot of trouble trying to think of a solution for this and I don't want to just add a many to many field for users to the movie table that I have without understanding if and why it is a good/bad approach.
How about something like:
class User(...):
first_name = models.CharField(...)
....
class Movie(models.Model):
title = models.CharField(...)
...
class Favorite(models.Model):
user = models.ForeignKey('User', related_name='favorites', ...)
movie = models.ForeignKey('Movie', related_name='favorites', ...)
Then we can do:
# a particular user's favorite movies:
user = User.objects.get(id='the_user_id')
user.favorites.values('movie')
# number of users who have favorited a particular movie:
movie = Movie.objects.get(id='the_movie_id')
movie.favorites.count()
Please am really need you guys help on how to use Django to create Multi-user Account.
e.g Student, Lecturers, and Department login page(Admin).
in this system, the department will be the Admin to register the lecturers in order to have access and why the Student register on their own.
Am design a project titled Online Assignment Submission System
(it is my final year Project). I really need you guys help on how to go about it using Django.
There are multiple options to deal with the user model in Django:
You could subclass AbstractUser or AbstractBaseUser and add a choice field if the user is a student, teacher, etc.
Linking back from a related 'Profile' model. This comes in handy if you want different types of users to have different fields.
models.py:
from django.conf import settings
from django.db import models
class StudentProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
subjects = models.ManyToManyField(Subject)
has_returned_books = models.BooleanField(default=False)
class TeacherProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
salary = models.IntegerField()
hours_per_week = models.IntegerField()
# ... other profiles for department, etc.
Using this approach, you can query fields with the ORM:
user.teacherprofile.salary or user.studentprofile.subjects.
When you have implemented your models you should read about the permission system in Django. You can limit access to logged-in users with help of a decorator or mixin.
Do some more research and come back asking specific question with examples of your recent work. The more work you put into the question, the more people will help you. Good luck!
I read the documentation about many-to-many relationships and the examples. What I could not find is a hint on where to put the ManyToManyField. In my case I have an extended user model Client and a model Pizza. Every client may mark one or more pizzas as favourites. Those are my two models:
from django.db import models
from django.contrib.auth.models import User
class Client(models.Model):
user = models.OneToOneField(User)
#? favourite_pizza = models.ManyToManyField()
class Pizza(models.Model):
name = models.CharField(max_length=255)
#? favourite_pizza = models.ManyToManyField()
In what model should I add the ManyToManyField? Does it matter?
PS The important information is how many favourite pizzas a client has (and which). It is less important how many clients marked a pizza as a favourite (and who). Consequently I would chose to put the ManyToManyField in the Client class.
From the Django documentation:
Generally, ManyToManyField instances should go in the object that’s going to be edited on a form.
Technically it does not matter. The question is from which model-side you will query the database.
I still have a lot to learn about Django models, so be gentle.
Consider this model:
from django.db import models
from django.contrib.auth.models import User
class Community(models.Model):
users = models.ManyToManyField(User)
class Portal(models.Model):
community = models.ForeignKey(Community, blank=True, null=True)
class Page(models.Model):
portals = models.ManyToManyField(Portal, null=True)
So a Page can be in many Portals. Each Portal has a Community and a Community has many users.
Now I'm trying to find all the users related to a single page:
def allowed_users(self):
return User.objects.filter(community__in=Community.objects.filter(portal__in=self.portals.all()))
This works, but I'm sure there is a more efficient way of doing it. Possibly with Q or F.
Any help is appreciated.
You can use the double-underscore syntax to traverse relationships. Assuming allowed_users is a method on Page:
User.objects.filter(community__portal__page=self)
I intend to create a teaming system, where each team may contain multiple contestants. The contestants is actually auth.User. Something similar to:
Team:
Contestant1
Contestant2
.
.
ContestantN
Since a contestant is actually a user which I cannot modify to have a foreignkey to team. What is the best way to achieve this?
The ways I though was:
Create a OneToOne profile for user which points to a team.
Define a ManyToMany relationship between user and team where user has to be unique.
A Pause
I am redesigning the structure of my application, so I will rephrase the question again
Thanks for your replies, I will consider them and see if one of them fits.
You can do this:
class Team(models.Model):
contestants = models.ManyToManyField(User, through='Contestant')
class Contestant(models.Model):
team = models.ForeignKey(Team)
user = models.ForeignKey(User)
[here go Contestant data fields]
This allows one user to take part in different teams, but if you don't want to allow this, you can add unique=True to Contestant.user.
The best way would be to extend the functionality of default accounts and create a new user model. The new user model can then have a foreign key to team. Like this.
class UserExtended(models.Model):
def __unicode__(self):
return self.user.username
user = models.OneToOneField(User, unique=True)
team = models.ForeignKey(Team)
User.profile = property(lambda u: UserExtended.objects.get_or_create(user=u)[0])
Now you can use the "UserExtended" in place of normal User.
I would create a contestants field on the Team model like so:
from django.contrib.auth.models import User
contestants = models.ManyToManyField(User)
You can't specify unique=True on a ManyToManyField. The good news is that it won't add the same contestant to the same team twice so you won't need to check if the contestant is unique.
I would say your best bet is to create a Contestant model. You'll probably end up needing to store more information about a contestant that is team-specific but separate from a player (such as whether the contestant is a starter, the contestant's number, and so on). Creating a Contestant model allows you to store that information separate from the User, and you would have a ForeignKey in the Contestant model referencing Users, and another ForeignKey in the Contestant model referencing Teams.