How to define one to many relationship in django - python

I have a condition that has one to many relationship scenarios because I will have multiple projects inside one account.
models.py
class Account(models.Model):
name = models.CharField(max_length=255, default='')
class Project(models.Model):
account = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
how can I manage this scenario, currently I'm getting the following error:
django.db.utils.ProgrammingError: relation "project_account_id_7d9b231b" already exists

account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True)

Related

Added a Non-Nullable Field in Django After Creating Entries That Didn't Have That Field; Operational Error, No Such Field

In my models, I added the class Source:
class Source(models.Model):
profile = models.ForeignKey('Profile', on_delete=models.CASCADE, null=True, default=False, blank=True, related_name='+')
project= models.ForeignKey('Project', on_delete=models.CASCADE, null=True, default=False, blank=True, related_name='+')
team = models.ForeignKey('Team', on_delete=models.CASCADE, null=True, default=False, blank=True, related_name='+')
department = models.ForeignKey('Department', on_delete=models.CASCADE, default=False, blank=True, null=True, related_name='+')
def __str__(self):
return str(self.id)
For testing purposes, I added a few entries for posts in the Django admin page,
and then went back into my classes: Post, Profile, Department, Team, and Project, and added:
sourceID = models.ForeignKey('Source', default='1', on_delete=models.CASCADE, related_name='+', null=False)
for each class.
My problem is that when I go in the Django admin page to alter the database (i.e. create a new post) I get the following error:
Also, when I go to migrate my changes, I keep getting this warning:
HINT: Configure the DEFAULT_AUTO_FIELD setting or the LeadsConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
I would like to be able to create new entries in my database without the operational error. I've tried changing the null value = True, but this is counterintuitive and doesn't yield any change, surprisingly. I think the best way would be to delete the whole database, which I've tried to research and only found MYSql code solutions. What is the best course of action?

How to fix manytomany field in django

How to make a one to many relationship in Django/Mysql?
I have an identical situation to this post, yet, my django returns errors on the admin page:
get() returned more than one order2pizza-- it returned 5!
order2pizza with that pizza already exists.
My mysql database have composite keys on a tertiary table to order and pizza to link multiple pizzas to an order.
models.py:
class Orders(models.Model):
order_id = models.AutoField(primary_key=True)
order_name = models.CharField(max_length=100, blank=True, null=True)
class Pizza(models.Model):
Pizza= models.AutoField(primary_key=True)
Pizza_name= models.CharField(max_length=50, blank=True, null=True)
class order2pizza(models.Model):
order = models.ManyToManyField(Orders, models.DO_NOTHING, )
pizza_id= models.IntegerField()
class Meta:
unique_together = (('order ', 'pizza_id'),)
A many-to-many relation can be expressed in two ways. First, you can manually specify a "join" model, like this:
class Orders(models.Model):
order_name = models.CharField(max_length=255, blank=True)
class Pizza(models.Model):
Pizza_name= models.CharField(max_length=255, blank=True)
class Order2Pizza(models.Model):
order = models.ForeignKey(Order, models.CASCADE)
pizza = models.ForeignKey(Pizza, models.CASCADE)
class Meta:
unique_together = ['order ', 'pizza']
This is useful if you want to put extra fields on the Order2Pizza model. A field named quantity would be very useful in your example.
The second option is to use a ManyToManyField. This will automatically create the join model for you:
class Orders(models.Model):
order_name = models.CharField(max_length=255, blank=True)
pizzas = models.ManyToManyField('Pizza', related_name='orders')
class Pizza(models.Model):
Pizza_name= models.CharField(max_length=255, blank=True)
In your original question you put the ManyToManyField on the Order2Pizza model, which is nonsensical.
However, the source of your bug is probably your manual inclusion of several *_id fields. Don't do that. They will always be created automatically by Django and you should never have to specify them manually. Instead, try the two options above and see how they work.

Django Operational Error: foreign key mismatch

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!

How to access ForeignKey-Objects in Django

Every user in my Django project has a list of Reports. I now want to display the user his list of reports. But how can I get all receipts which belong to a specific user?
Report-Model
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Report(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False)
department = models.CharField(max_length=256, blank=False, null=False)
workshop = models.CharField(max_length=256, blank=False, null=False)
teacher = models.CharField(max_length=256, blank=False, null=False)
hours = models.IntegerField(blank=True, null=False, default=4)
date = models.DateField(blank=True, null=False)
For example, if you want to get the reports of the logged in user you can do the following.
reports = Report.objects.filter(user=request.user)
this should return all the reports of a user. Similarly change the request.user object to another user object and is should work fine as well.
Note - I am assuming "reports" and "receipts" are the same the thing here cause there's no mention of receipt attribute in your model.

Want to achieve searching function in django admin page for multiple tables

I am currently working on django 2.0.2 admin page. I have three tables, which are 'metabolites', 'gene' and 'reactions.' The structure of each class is defined as below:
class Genes(models.Model):
id = models.CharField(primary_key=True, max_length=255)
name = models.CharField(max_length=255, blank=True, null=True)
notes = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'Genes'
class Metabolites(models.Model):
id = models.CharField(primary_key=True, max_length=255)
name = models.CharField(max_length=255, blank=True, null=True)
compartment = models.CharField(max_length=255, blank=True, null=True)
charge = models.CharField(max_length=255, blank=True, null=True)
formula = models.CharField(max_length=255, blank=True, null=True)
notes = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'Metabolites'
class Reactions(models.Model):
id = models.CharField(max_length=255, primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
metabolites = models.TextField(blank=True, null=True)
lower_bound = models.CharField(max_length=255, blank=True, null=True)
upper_bound = models.CharField(max_length=255, blank=True, null=True)
gene_reaction_rule = models.TextField(blank=True, null=True)
subsystem = models.CharField(max_length=255, blank=True, null=True)
notes = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'Reactions'
As you can see, the 'reaction' class also included 'metabolites' component. A typically reaction actually involved more than two metabolites. What I want to do is, create a search field on the admin page(not the page of each class), and when I type in the reaction id, the searching result can display the reaction and all the involved metabolites, and when I type in a metabolites, the searching result can display this metabolite's information and all reactions this metabolites involved.
Is that possible? Can somebody tell me how to do this?
Thank you for helping me!
EDIT:
This describes the "old school" way of accomplishing this. This appears to be a use case for django's many to many fields. I have not run into this need in my project; so, I have not, yet, studied up the many to many capabilities in django. I recommend reading the django docs for how to use many to many fields.
The way described here will accomplish the desired connections in the data. However, I suspect that the django admin will be easier and more straightforward to set up using a many to many field.
end edit
You want to make another model for metabolites_in_reaction that only contains its own primary key, a foreign key to the reaction and foreign key to metabolites.
class ReactionMetabolites(models.Model):
reaction = models.ForeignKey(Reactions, on_delete=models.CASCADE)
metabolite = models.ForeignKey(Metabolites, on_delete=models.CASCADE)
A many to many field may also be appropriate here; I have not really figured out the many to many fields yet.
Edit 2:
After making these changes in your models, you will need to make and apply migrations to apply the changes to your database.
python manage.py makemigrations
python manage.py migrate

Categories