I have two models as shown below. ArticlePost is related to Article by a Foreign Key. I'm wanting to remove name as a primary key on Article and instead have the Django default id field. What is the best steps to do this so that all related ArticlePosts will maintain the correct Foreign Key to Article?
class Article(models.Model):
name = models.CharField(max_length=200, primary_key=True)
class ArticlePost(models.Model):
article = models.ForeignKey(Article, null=False, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
comment = models.TextField(blank=True)
Related
one of the questions that came to my mind is that in a many-to-one relationship in Django, where should the foreign key be located? I mean, it should be in many or in part one?
For example, we have two classes, post and comment: in this case, where should the ForeignKey be located in the comment or post class?
post model :
class post(models.model):
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ManyToManyField("PostCategory", blank=True)
caption = models.CharField(max_length=2000)
comment model :
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('user'), on_delete=models.CASCADE)
text = models.TextField()
Now here is the comment field where the foreign key should be defined?
Foreign key must be used on the "Many" side of the Many-to-one relationships.
In your question, you have Post and Comment models. Since each post can have many comments, you should put a foreign key into your Comment model.
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
I have two models:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="categories")
name = models.CharField(max_length=30, unique=True, primary_key=True)
class Todo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='todos')
# TODO: Add confirmation before deleting category
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name="todos_in_category", null=True)
item = models.CharField(max_length=50)
added = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
Previously, Category's PK was the default id, however, I changed it to the name field. When I ran the migrations, i received the operational error. Thinking that it was perhaps due to a conflict between the existing id fields and the new primary key, I cleared the data in the database but with no success. Any ideas as to what could be the issue here? Thanks!
I want to create database model in django and define a foreign key. All the example I see in internet have following syntax.
attr = models.ForeignKey(Entity)
However I want a foreign key to be linked with single attribute from another entity and not the whole entity.
I have following models:
class User(models.Model):
user_id = models.PositiveIntegerField(primary_key=True)
password = models.CharField(max_length=20)
email = models.EmailField()
........
class ContentItem(models.Model):
content_id = models.PositiveIntegerField(primary_key=True)
title = models.CharField(max_length=100)
description = models.TextField()
.........
author_id = models.ForeignKey(User, on_delete= models.CASCADE)
Here, I want ContentItem.author_id to be foreign key for User.user_id and not the whole User model. While entering value for author_id, I simply want to enter plain id (1,2,3) and not all the instance of User
Sorry if the question is very general and thanks in advance
You should name your fk field like:
author = models.ForeignKey(User, on_delete= models.CASCADE)
because Django will create the attribute author_id automagically and
content_item.author_id
will give you access to the id of the user directly without an extra db hit. With your naming, you can access the id directly through author_id_id.
You have to override the str(self) method inside your models class.
Ex.
models.py
class User(models.Model):
.
.
.
def __str__(self):
return fâ{self.attribute-name}
Where attribute-name is name of attribute you want to reference.
Enjoy the coding đđ
I have two tables that have already been populated(~1700 entries each):
class Drug(models.Model):
drug_id = models.AutoField(primary_key=True)
name_generic = models.TextField(blank=True, null=True)
indication = models.TextField(blank=True, null=True)
approval_company = models.TextField(blank=True, null=True)
class Company(models.Model):
name = models.TextField(primary_key=True)
research = NullBooleanField()
successor = models.TextField(blank=True, null=True)
founded = models.DateField(blank=True, null=True)
I have it set up so that approval_company in Drug is a match to name in Company. What I would like to do is to make the approval_company field on Drug that has a Foreign Key relationship to Company.
After setting
approval_company = models.ForeignKey(Company), and then adding the constraint in postgres, I get a ProgrammingError whenever I try to visit the django admin page for Drug.
Django tries to look for an approval_company_id field that does not exist. How would I go about adding this Foreign Key relationship on a table that already has many values?
I have this setup in my models:
class Author(models.Model):
name = models.CharField(max_length=100)
class Topic(models.Model):
name = models.CharField(max_length=100)
class Article(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, null=True, blank=True)
topics = models.ManyToManyField(Topic, null=True, blank=True)
Given an author, I want to know which topics he wrote about:
def author_info(request, pk):
author = get_object_or_404(Author, pk=pk)
topics = ????
If I had specified a through field, I could use that, but now Django makes the through field for me, and since its supposed to be transparent, Id rather not reference the field (unless there is a proper Django construction for that).
Use Lookups that span relationships:
topics = Topic.objects.filter(article__authors=author).distinct()
Note: you have to use distinct here, because the same topic can be selected by different articles.