Django model design issue with relationship - django

I have an problem where I can’t decide how to design the models for the following scenario
I want to create a companies table that will hold a list of companies. This table will have a comment field in it
I want that comment field to be able to hold multiple comments that are dated
A company can have multiple comments but a comment can only belong to only one company
Here the Comments table
class Comments(model.Models):
date = models.DateField(auto_now_add=True)
comment_text = models.TextField(required=True)
If I create the Companies table like this;
class Companies(models.Model):
name = models.CharField(max_length=30)
country = models.CharField(max_length=30)
comment = models.ForeignKey(Comments, on_delete=models.SET_NULL, null=True)
Then I can only attach one comment to one specific row of the Companies table
If I create the Companies table like this;
class Companies(models.Model):
name = models.CharField(max_length=30)
country = models.CharField(max_length=30)
comment = models.ManyToManyField(Comments)
Then a comment can belong to multiple companies which I don’t want.
In the Django documentation https://docs.djangoproject.com/en/2.0/topics/db/examples/ there is only one other options left which is the one-to-one mapping and this is clearly not what I want.
How can achieve what I want ?

You should do this.
class Company(models.Model):
name = models.CharField(max_length=30)
country = models.CharField(max_length=30)
class Comment(models.Model):
company = models.ForeignKey(Company, related_name='comments', on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
comment_text = models.TextField()
When accessing comments of a certain company, It will be;
comments = company.comments.all()

Just put the ForeignKey on Comment, pointing to Company. This does exactly what you want.

Related

Django Query: How to find all posts from people you follow

I'm currently building a website with the Django Framework. I want on the homepage of my website to display all posts made by people the user is following. Here are the classes for Profile, Story and Follow:
class Profile(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30, null=True)
last_name = models.CharField(max_length=30, null=True)
class Follow(models.Model):
following = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name="following")
follower = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name="follower")
follow_time = models.DateTimeField(auto_now=True)
class Story(models.Model):
author = models.ForeignKey('accounts.Profile', on_delete=models.CASCADE, related_name="author")
title = models.CharField(max_length=50)
content = models.TextField(max_length=10000)
As you can see Follow uses two Foreign Keys to represent the following and the follower. Is there a way to query all stories from people the user is following?
I really don't know what to filter. Or is this maybe a job for aggregation? If someone could help me, that would be awesome!
following_feed = Story.object.filter(???).order_by('-creation_date')
One can use double underscores (__) to look "through" relations (like ForeignKeys, etc.).
So here we can filter like:
Story.objects.filter(
author__following__follower=my_profile
)
So by using author we obtain a reference to the Profile of the author, then with following we look at the Follow model and then finally with follower we again obtain a reference to Profile(s): the profile(s) of the follower(s).
my_profile of course need to be substituted with a Profile object (the profile of the person that is a follower of the authors of the Storys you wish to obtain).
This will generate a query like:
SELECT s.*
FROM story AS s
JOIN follow AS f ON f.following_id = s.author_id
WHERE f.follower_id = 123
where 123 is the id of the my_profile.
If a person is following another person multiple times (here this can happen since you do not enforce that the follower, following tuples are unique in the Follow model), then the corresponding Storys will be yielded multiple times.
It is therefore probably better to add a unique_together constraint in the Follow model:
class Follow(models.Model):
following = models.ForeignKey(
'Profile',
on_delete=models.CASCADE,
related_name="following"
)
follower = models.ForeignKey(
'Profile',
on_delete=models.CASCADE,
related_name="follower"
)
follow_time = models.DateTimeField(auto_now=True)
class Meta:
unique_together = (('following', 'follower'), )
It might also be worth to see the Follow model as the through model of a ManyToManyField [Django-doc].
Note that I haven't tested the code I am posting so tell me if something is missing.
First, you need to get all the Profiles that your users follow. Then you have to get the Stories that they have.
followed_people = Follow.objects.filter(follower=current_user).values('following')
stories = Story.objects.filter(author__in=followed_people)

Django Models: One-to-Many Relationships, Reaching Across Tables -- How Can I get All Book objects with Reviews?

My Problem:
I have a handful of django models which are setup with various one-to-many relationships. I am trying to retrieve all Books which have a Review (I don't want to retrieve any books whom have no Reviews). Although what I'm trying to do seems relatively straight forward, I'm having real difficulty accomplishing my goal. It seems I may not properly understand how to reach across tables, and any advice anyone could provide in helping me better understand how to get all all Book objects which have a Review stored.
My Models:
class User(models.Model):
"""Creates instances of a `User`."""
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.CharField(max_length=50)
password = models.CharField(max_length=22)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager() # Attaches custom `UserManager` methods to our `User.objects` object.
class Author(models.Model):
"""Creates instances of a `Author`."""
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Book(models.Model):
"""Creates instances of a `Book`."""
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE) # ties us into an author for the book. if author deleted, books delete too.
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Review(models.Model):
"""Creates instances of a `Review`."""
description = models.CharField(max_length=500)
user = models.ForeignKey(User, on_delete=models.CASCADE) # ties to user, if user deleted, deletes all user reviews
book = models.ForeignKey(Book, related_name="reviews") # book for review
rating = models.IntegerField() # user rating between 1-5
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = ReviewManager() # Attaches 'ReviewManager' to `Review.objects` methods.
What I've tried:
I've tried giving a related_name="reviews" to my Review.book property, and I've tried accessing reviews via Book.objects.all().reviews_set.all() or similar such queries, using _set.all() and am probably missing something / doing it incorrectly.
Desired Goal:
Retrieve all Book objects, whom have a Review attached to them (not retrieving Book objects whom have no Reviews).
Can anyone help point me in the right direction or tell me what I'm doing wrong? Thank you for your time reading!
Here's my best solution for gathering all books, whom have at least one review. This seems to be accomplishing my needs and answered my original question:
Book.objects.filter(review__gte=1).distinct()
This is saying, from Book model, get any books whom have a review gte (greater than or equal to) 1 -- and make sure they are distinct() ie, no duplicates.

Get all related field in Django model

I am struggling to understand how one-to-many and many-to-many relation works in Django model. My schema looks something like this so far, I am open for suggestions to make it better.
A many-to-many relation between users and team. Also, there will be schedules that belong to a particular user of a team.
This is how my model looks like so far,
class Team(models.Model):
tid = models.AutoField(primary_key=True)
team_name = models.CharField(max_length=30)
manager_name = models.CharField(max_length=30)
class Schedule(models.Model):
sid = models.AutoField(primary_key=True)
user = models.OneToOneField(User)
date = models.DateField()
start_time = models.TimeField()
end_time = models.TimeField()
pay_rate = models.CharField(max_length=30)
location = models.CharField(max_length=50)
class BelongsTo(models.Model):
bid = models.AutoField(primary_key=True)
user = models.OneToOneField(User)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
Question: I want to get the information of each user, what are their schedules and which team each schedule belongs to. How would I to do it? I have tried BelongsTo.objects.select_related().all(), but it is not working for me.
Note: I am open for suggestions, if something is wrong with my schema or model or the approach, please let me know.
BelongsTo is seems like utility table.So
BelongsTo.objects.all().values('user', 'team__team_name', 'schedule')
Your schema looks almost right, but I would modify it a little bit. In particular, I will change how Schedule is implemented. Instead of having a sid in the User Belongs To join-table, I would include the user and team in the Schedule table as foreign keys.
This is how the Django models should then look like:
class User(models.Model):
username = models.CharField(max_length = 200)
# put other fields like password etc. here
class Team(models.Model):
team_name = models.CharField(max_length=30)
manager_name = models.CharField(max_length=30)
user = models.ManyToManyField("User")
class Schedule(models.Model):
user = models.ForeignKey("User")
team = models.ForeignKey("Team")
date = models.DateField()
start_time = models.TimeField()
end_time = models.TimeField()
pay_rate = models.CharField(max_length=30)
location = models.CharField(max_length=50)
Note the following:
You don't need to have a primary key field in the models because Django adds a primary key field called pk or id automatically.
Note the absence of the User Belongs To model. Django implements join-tables like User Belongs To automatically when you use a ManyToManyField. See the Django docs on many-to-many relationships.
You also don't need on_delete = models.CASCADE on ForeignKey fields, because this is the default behavior.
To see how to get information about users, teams and schedule from this configuration of models, consult the Django documentation on making db queries. It's quite easy.

Understanding ManyToMany fields in Django with a through model

I'm having trouble understanding the use of ManyToMany models fields with a through model. I can easily achieve the same without the ManyToMany field. Considering the following from Django's docs:
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = 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()
invite_reason = models.CharField(max_length=64)
What I don't understand, is how is using the ManyToMany field better than simply dropping it and using the related manager. For instance, the two models will change to the following:
class Group(models.Model):
name = models.CharField(max_length=128)
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='members')
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
What am I missing here?
You're right, if you define the membership table explicitly then you don't need to use a ManyToManyField.
The only real advantage to having it is if you'd find the related manager convenient. That is, this:
group.members.all() # Persons in the group
looks nicer than this:
Person.objects.filter(membership_set__group=group) # Persons in the group
In practice, I think the main reason for having both is that often people start with a plain ManyToManyField; realize they need some additional data and add the table explicitly; and then continue to use the existing manager because it's convenient.
So I just wanted to add to anyone who is looking at this and may want another example to save them research. For one, I think it's important to note that in OP's questions, he should of removed the Group model not the People model and removed the matching field from the Membership model. That way, the model goes back to it's original meaning.
When looking at a many-to-many relationship, the through field can almost be contrived as the "why" to the many-to-many relationship. If we give the nomenclature a different name, it might change what the reader sees:
class Person(models.Model):
name = models.CharField(max_length=128)
class Club(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='RegistrationReceipt')
class RegistrationReceipt(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
club = models.ForeignKey(Club, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
paid_dues = models.BooleanField(default = True)
fee_payment_date = models.DateTimeField()
Now, you can imagine yourself adding all sorts of logic whenever a member joins this club. When they joined? Why did they join? Did they pay? When is their payment date? etc. You can obviously tackle this relationship in different ways, but you can see more clearly the use of "through" in a Many-to-Many relationship.
Also, for those that know SQL. The through attribute/field is the way you customize the intermediary table, the one that Django creates itself, that one is what the through field is changing.
I have some problem with the answer from Kevin Christopher Henry.
I don't think that the equivalent of the group.members.all() without a through="members" is Person.objects.....
Instead I think it is group.person_set.all() if the M2M field is on Person side. Or group.persons.all() if the M2M field is inside Group.
But I think without through=.. you have no control over the created table. It contains and will contain just 2 fields: both ID's of the related rows.
But with through=.. you can create the model yourself and add (now or later) the additional fields, which often can have a good reason. Example of such field: valid_from = DateField(), or so.

Django model - set up a "has_many_through" relationship

Looking for advice on setting up this model.
This job board app has Company, Location, and Job. They should have the following relationships:
A Company can have multiple locations
A Company can have multiple jobs
A Job can have only one Company
A Job can have multiple locations, BUT each Location must be valid for the job's Company
I'd like to create a model that reflects these relationships. I think something like this might work:
class Company(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
class Location(models.Model):
is_primary_location = models.BooleanField()
address = models.CharField(max_length=200)
company = models.ForeignKey(Company)
class Job(models.Model):
title = models.CharField(max_length=200)
company = models.ForeignKey(Company)
location = models.ForeignKey(Location)
But I would really like the "Job has Location(s) through Company" relationship to be enforced. The model doesn't enforce it; I think I'd have to filter the valid Locations when data is displayed, and I'd like to avoid that.
Thanks very much!
Take a look at ForeignKey.limit_choices_to.
This allows you to filter the available choices and is enforced in ModelForm. Since you already have the company foreign key in your Job model, you should be able to use that to filter the choices.
I ended up using https://github.com/digi604/django-smart-selects and wrote the model like this. I don't think limit_choices_to works in this case (according to other SO threads)
from smart_selects.db_fields import ChainedForeignKey
class Company(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
class Location(models.Model):
is_primary_location = models.BooleanField()
address = models.CharField(max_length=200)
company = models.ForeignKey(Company)
class Job(models.Model):
title = models.CharField(max_length=200)
company = models.ForeignKey(Company)
location = ChainedForeignKey(
Location,
chained_field="company",
chained_model_field="company",
show_all=False,
auto_choose=True
)