Many foreign keys in a model, better way to do models? - django

I'm kind of new to django. While writing the models for an app I'm doing, I felt like I was doing something wrong because of all the foreign keys I was using for a single model (ticket model to be specific)
My thinking at the beginning was that I wanted each Ticket to keep the information on it's creator, what team this ticket is assigned to and the comments made on the ticket. And other information that don't need foreign keys. Am I doing this right ? I dont know why, but I feel like there is a better way.
class Team(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=2000)
members = models.ManyToManyField(User, through='Team_members')
def __str__(self):
return self.name
class Ticket(models.Model):
name = models.CharField(max_length=200)
creator = models.ForeignKey(User, on_delete=models.CASCADE)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
comments = models.ForeignKey(Comment, on_delete=models.CASCADE)
#worker = models.ForeignKey(User, on_delete=models.CASCADE) *to be finished
description = models.CharField(max_length=500)
status = models.BooleanField(default=False)
date_opened = models.DateTimeField('date opened')
date_closed = models.DateTimeField('date closed',null=True, blank=True)
def __str__(self):
return self.name
class Team_member:
team = models.ForeignKey(Team)
user = models.ForeignKey(User)
date = models.DateTimeField('date joined')
class Comment:
text = models.CharField(max_length=2000)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.text

Your question actually has very little (like, nothing?) to do with Django.
Please read about database normalization, it should answer your questions.
Regarding your models, I could notice the following:
Your models look quite good. Don't be afraid of foreign keys, they are the main reason you use a relational database :)
I assume, User might be a member of a Team (service?) or somebody who opens a ticket. If so: when you will have worker foreign key, you most likely won't need team in the Ticket model. It will be redundant, as worker would have a relation to Team.
Nitpicking: Team_member is not pythonic, a PEP8 compliant version would be TeamMember

Related

django unique_for atributes in models

In the past, I think there was a model atrtibute named unique_for to define a foreignKey but I can't find it anymore.
Suppose a model named Recommendation. A User can recommend many websites but only one by domain. So, I wanted to set a unique_for('user', 'recommendation.domain') or something like like this.
What's the current way to do it ?
Recommendation Model:
class Recommendation(models.Model):
is_recommended = models.BooleanField(default=True)
what = models.ForeignKey('Website', on_delete=models.CASCADE)
who = models.OneToOneField(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
why = models.CharField(max_length=255, null=True, blank=True)
when = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-when"]
User Model is the Django built in.
Thanks
I've found my answser.
The attribute is unique_together and not unique_for

Django querying foreign key from backward

I am trying to query from backward: at fist see my models:
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
body = models.TextField()
category = models.ForeignKey('blog.Category', on_delete=models.CASCADE)
def __unicode__(self):
return '%s' % self.title
class Category(models.Model):
name = models.CharField(max_length=100, db_index=True)
I have many category and many post, one category name is tech I am trying to get all the post those are in tech category.
I tried like this. Category.objects.filter(contain__exact='tech') but it is not work anymore.
Can anyone help me to figure get it done?
Best way to get all the post in tech category using foreign key.
tech_blogs = Blog.objects.filter(category__name__icontains='tech')
and also change
category = models.ForeignKey('Category', on_delete=models.CASCADE)

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.

Storing data in different tables or using bool fields

I have an Article table
class Article(models.Model):
"""
Model to keep articles
"""
ext_id = models.UUIDField(primary_key=True, db_index=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=255, unique=True, db_index=True)
content = models.TextField()
summary = models.TextField()
img_url = models.URLField(max_length=200)
author = models.CharField(max_length=50, blank=True, null=True)
sport = models.ForeignKey('Sport')
posted_on= models.DateTimeField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return "%s by %s" % (self.title, self.author)
A table where I store articles liked by a user :
class LikedArticle(models.Model):
"""
Articles that a user wants to read
"""
ext_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
article = models.ForeignKey(Article)
profile = models.ForeignKey(Profile)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
and unliked :
class UnlikedLikedArticle(models.Model):
"""
Articles that a user does not want to read
"""
ext_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
article = models.ForeignKey(Article)
profile = models.ForeignKey(Profile)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
Now here, both the tables liked and unliked, are structurally the same.
I find it better to store it like this instead of storing say a bool field called is_liked because I exactly know what data I am storing. So I don't have to query a huge set of articles when I know that I am only interested in LikedArticle.
Is this the correct approach ? I am only confused because structurally they look the same and something doesn't feel right about this design.
the best approach that i recommend is to use one table and add is_liked field. (and add index to this field, so you get high performance queries)
but if still you want to use your approach with 2 table, then you need to fix your design.
use one abstract model that has all fields, and the Like and Unlike tables inherit from the abstract model
class ActionOnArticle(Model):
your fields here..
class Meta:
abstract = True
class LikedArticle(ActionOnArticle):
class UnLikedArticle(ActionOnArticle):
I think is_liked is not a good option if you want to save other information per profile, like that: who liked what and when and so on. If you want to lose those info so my suggestion is to use many to many relationship and the article model will be something like that:
class Article(models.Model):
"""
Model to keep articles
"""
ext_id = models.UUIDField(primary_key=True, db_index=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=255, unique=True, db_index=True)
content = models.TextField()
summary = models.TextField()
img_url = models.URLField(max_length=200)
author = models.CharField(max_length=50, blank=True, null=True)
sport = models.ForeignKey('Sport')
posted_on= models.DateTimeField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
likes = models.ManyToManyField(Profile)
unlikes = models.ManyToManyField(Profile)
def __unicode__(self):
return "%s by %s" % (self.title, self.author)
https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_many/
While if you want to save the info mentioned at the beginning of my reply, I think #Eyal answer is fine
I'd use the "is_liked" BooleanField and filter on it to just get the liked or disliked articles. Filtering on a BooleanField (add db_index=True on the field options) will be extremely fast with any decent database so you are very unlikely to get a noticable performance increase using separate tables even if they were huge.

Tag system for Django

I am building a Quiz app where a user (Content Creator or Author) can create quizzes (choice based questions and their solutions) from a specific domain. These quiz can be attempted by other users (Consumers - not yet implemented).
To allow quiz consumers to be able to search questions based on specific domains of their interest (and to add granularity to the quiz content), I am implementing a tagging system attached to the questions.
Here are my models:
class question(models.Model):
ques_id = models.AutoField(primary_key=True)
ques_text = models.TextField(max_length=1024, blank=False)
ques_author = models.ForeignKey('author')
ques_created = models.DateField(auto_now_add=True)
ques_dscore = models.IntegerField()
ques_bloom = models.CharField(max_length=3)
ques_subject = models.CharField(max_length=3)
ques_type = models.CharField(max_length=1)
ques_flags = models.CharField(max_length=16)
ques_quiz = models.ManyToManyField('quiz')
def __unicode__(self):
return self.ques_text
class choice(models.Model):
choice_id = models.AutoField(primary_key=True)
choice_text = models.CharField(max_length=256, blank=False)
choice_ques = models.ForeignKey('question')
choice_ans = models.BooleanField(default=False)
choice_tags = models.CharField(max_length=32)
def __unicode__(self):
return self.choice_text
class answer(models.Model):
answer_id = models.AutoField(primary_key=True)
answer_text = models.TextField(max_length=1024)
answer_ques = models.ForeignKey('question')
answer_choice = models.ForeignKey('choice')
answer_tags = models.CharField(max_length=128)
class author(models.Model):
user = models.OneToOneField(User)
domain = models.CharField(max_length=16)
def __unicode__(self):
return self.user.username
# a table for storing all the tags
class tags(models.Model):
tags_id = models.AutoField(primary_key=True)
tags_text = models.CharField(max_length=16)
def __unicode__(self):
return self.tags_text
# table that connects tags with question attached to the tag
# from all the research on the web, it can be infered that
# 3NF tagging (Toxi Solution) is the best way to go
# good for inserts but slow on selects
class tagcon(models.Model):
tagcon_id = models.AutoField(primary_key=True)
tagcon_tags = models.ForeignKey('tags')
tagcon_ques = models.ForeignKey('question')
I have currently applied the 3NF tagging Toxi solution. The issue is that a denormalized system would help in faster selects and a 3NF would be faster inserts but slow searches.
I am confused if I should use ManyToMany field type for tags. Could someone enlighten if it would be better to use a ManyToMany field inbuilt in Django or implement the 3NF system as done?
This is already exactly the same as a ManyToManyField. The only difference is that adding the field would give you an explicit accessor from question to tag.
(Note, your models are very odd. There is absolutely no benefit in prefixing every field name with an abbreviated version of the model name; you can only ever access the field via the model anyway, so you would always be doing question.ques_text, which is redundant. And you shouldn't be defining your own PK fields unless you have a very good reason.)
In my opinion I suggest you try these 2 projects
django-tagging.
django-taggit.