how to reference to the django user model - django-models

hello i have a model named Assigned_problem in which a need to add two foreign keys of the model user in it. one foreign key represents the person who assigned the problem and the other foreign key represents the person to whom the problem is assigned. so in the course of updating the modifications done one the database structure i ave the following errors
mini_url.Assigned_problem.assigned_to: (fields.E305) Reverse query name for 'Assigned_problem.assigned_to' clashes with reverse query name for 'Assigned_problem .assigned_by'. HINT: Add or change a related_name argument to the definition for 'Assigned_problem.assigned_to' or 'Assigned_problem.assigned_by'.
THIS IS MY MODEL STRUCTURE
class Assigned_problem(models.Model):
assignation_status = models.IntegerField()
assigned_date = models.DateTimeField(auto_now_add=True, auto_now=False,
verbose_name="Assigned Date")
assigned_to = models.ForeignKey(User)
assigned_by = models.OneToOneField(User)
problem = models.OneToOneField('Problem')
def __str__(self):
return "{0}".'format'(self.problem.problem_content)

With
assigned_to = models.ForeignKey(User)
assigned_by = models.OneToOneField(User)
you declared two ForeignKeys to the model User. They're not distinguishable by their relation to User itself. Try to add a related_name attr for each of your foreign keys to User.
assigned_to = models.ForeignKey(User, related_name="User assigned to")
assigned_by = models.OneToOneField(User, related_name="User assigned by")
See the django docs

Related

How to use particular field of a model into another model, like I want to use sku as a foreign key in next model?

class Product(models.Model):
price=models.IntegerField()
no=models.IntegerField(default=0,null=True)
sku= models.CharField(max_length=100,default=0,null=True )
#Here I want to use sku into another model as a foreign key
In that case, the sku needs to be unique, and non-nullable, since otherwise it can not refer to a product properly, so:
class Product(models.Model):
price = models.IntegerField()
no = models.IntegerField(default=0, null=True)
sku = models.CharField(max_length=100, unique=True)
Then you can work with the to_field=… parameter [Django-doc]:
class Order(models.Model):
product = models.ForeignKey(Product, to_field='sku', on_delete=models.CASCADE)
Then if you use my_order.product_id, it will contain the sku of the product it refers to.

Join two models in django

I have two models with a unique key: EMAIL. For both of the models the field EMAIL is unique, but some of the emails of model A do not necessarily exist in model B. I would like to perform an inner join, but since I'm quite new to Django I have no idea how to do this.
You should define the Email model look like this
class Email(models.Model):
"""
Email model.
"""
email = models.EmailField(
unique=True,
error_messages={
'unique': "This email has already been registered."
}
)
def __str__(self):
return self.email
Then create 2 models related to Email model by using ForeignKey.
Or you just need to save email by using EmailField for each model.
class ModelA(models.Model):
"""
A model.
"""
email = models.EmailField(
verbose_name="Email",
unique=True,
)
...other fields
In Django, you need to make a relation between table in order to apply any type of join
class ModelA(models.Model):
email = models.EmailField(unique=True)
model_b = models.ForeignKey(to=ModelB, null=True, blank=True)
class ModelB(models.Model):
email = models.EmailField(unique=True)
then
data = ModelA.objects.filter(model_b__isnull=False)
Instance with same email id should be linked with each other.

How to fix ''Follow.s_id' is not a foreign key to 'Users'." in this model

I am new to Django framework, I am trying to build the following system which contains a user who follows multiple stocks and the stocks are followed by multiple people, I'm trying to create a composite key using an intermediate class, but I'm having this error.
class Stock(models.Model):
symbol = models.CharField(max_length=12, primary_key=True,default="")
name = models.CharField(max_length=64)
top_rank = models.IntegerField(null=True)
price = models.FloatField()
change = models.FloatField(null=True)
change_percent = models.FloatField()
market_cap = models.FloatField(null=True)
primary_exchange = models.CharField(null=True, max_length=32) # NASDAQ
followers = models.ManyToManyField('myapp.Users',through='Follow',through_fields=('u_id','s_id'))
class Users(models.Model):
user_id = models.IntegerField(primary_key=True,default="")
name = models.CharField(max_length=12)
class Follow(models.Model):
u_id=models.ForeignKey('Users',on_delete=models.CASCADE)
s_id=models.ForeignKey('Stock',on_delete=models.CASCADE)
myapp.Stock.followers: (fields.E339) 'Follow.s_id' is not a foreign key to 'Users'.
HINT: Did you mean one of the following foreign keys to 'Users': u_id?
myapp.Stock.followers: (fields.E339) 'Follow.u_id' is not a foreign key to 'Stock'.
HINT: Did you mean one of the following foreign keys to 'Stock': s_id?
The order of the through_fields [Django-doc] is incorrect. As specified in the documentation:
through_fields accepts a 2-tuple ('field1', 'field2'), where field1 is the name of the foreign key to the model the ManyToManyField is defined on (...), and field2 the name of the foreign key to the target model (...).
So that means the first item of the through_fields should be 's_id' here, since that refers to the Stock model, the model where you defined the ManyToManyField, and the second item should be 'u_id':
class Stock(models.Model):
# …
followers = models.ManyToManyField(
'myapp.Users',
through='Follow',
through_fields=('s_id','u_id')
)
That being said, you here do not need to define the through_fields here, since your Follow model contains exactly two ForeignKeys that point to different models. In fact you do not need to define a through=... model either, since it does not contain any extra fields.
Note that usually a ForeignKey does not contain an _id suffix, since Django will automatically add an extra field with the _id suffix that contains the primary key of the referenced value.
Therefore it might make more sense, to just define the models as:
class Stock(models.Model):
symbol = models.CharField(max_length=12, primary_key=True)
name = models.CharField(max_length=64)
top_rank = models.IntegerField(null=True)
price = models.FloatField()
change = models.FloatField(null=True)
change_percent = models.FloatField()
market_cap = models.FloatField(null=True)
primary_exchange = models.CharField(null=True, max_length=32) # NASDAQ
followers = models.ManyToManyField('myapp.User')
class User(models.Model):
user_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=12)
Note that models usually have a singular name, so User, instead of Users.

insert or update on table "app_job" violates foreign key constraint "app_job_user_id" DETAIL:Key (user_id)=(1) is not present in table "accounts_user"

I have used function based View to get data from post Request. I need to get many data that also include a primary key field too. I need to push data into two models. While doing so, I encountered error.
#accounts models.py
from django.db import models
class User(models.Model):
user_id = models.CharField(max_length=50,)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=200)
email = models.EmailField(max_length=254)
#app models.py
from accounts.models import User #from accounts models.py
class job(models.Model):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
......
#views.py
data = job(.....,map_link=map_link,user_id=user_id)
data.save()
info=User(name=name,email=email,phone=phone,user_id=user_id)
info.save()
Error Message: http://dpaste.com/03Z0EPB
enter image description here

Null value in Django ORM model object's primary key

I have a Django ORM model that needs to integrate with a legacy database. The model was generated via manage.py inspectdb, and the class definition is like so:
class ClientJob(models.Model):
id = models.AutoField(primary_key=True, db_column="id")
CustomerGuid = models.CharField(max_length=40, db_column='CustomerGUID', blank=True)
JobGuid = models.CharField(max_length=40, db_column='JobGUID', blank=True)
AgentGuid = models.CharField(max_length=40, db_column='AgentGUID', blank=True)
class Meta:
db_table = u'ClientJob'
The primary key id was originally defined as models.IntegerField(primary_key=True), but from my understanding of Django this needs to be an AutoField if I want it to automatically increment hence the change.
I can query for objects without any issues, but when I run into trouble when I attempt to create and save a new object. The following code throws an IntegrityError with the message "null value in column "id" violates not-null constraint".
new_job = ClientJob.objects.create(CustomerGuid=customer_guid, JobGuid=str(uuid4()), AgentGuid=agent_guid)
new_job.save()
I suspect (but by no means certain) that this might be because my ClientJob table's primary key depends on a custom sequence. The definition of the sequence is as follows:
CREATE SEQUENCE seq_client_job_id
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 11020
CACHE 1;
ALTER TABLE seq_client_job_id
OWNER TO ssa;
Any help shedding light on this will be much appreciated.
Simply delete or uncomment the id line in your modelclass - it should work like a charm.
class ClientJob(models.Model):
#id = models.AutoField(primary_key=True, db_column="id")
CustomerGuid = models.CharField(max_length=40, db_column='CustomerGUID', blank=True)
JobGuid = models.CharField(max_length=40, db_column='JobGUID', blank=True)
#...

Resources