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

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.

Related

How to write a Django model form to include selected fields from multiple tables

There are many questions about building model forms from multiple tables, but I couldn't find a solution to my problem.
Background:
In model.py I have 3 simple models with 1-many relationship
class site(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
sitename = models.CharField(max_length=150)
site_address = models.CharField(verbose_name='Address', max_length=200, null=True, blank=True)
class block(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
blockname = models.CharField(max_length=150)
sitename = models.ForeignKey(site, on_delete=models.CASCADE, )
class quarter(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
quartername = models.CharField(max_length=150)
blockname = models.ForeignKey(block, on_delete=models.CASCADE, )
I have separate forms for each model - where user can add, edit and delete and site, block using standard djando modelform and modelformset.
The challenge I'm facing is with creating a quarter form. On a quarter from I want user to select a site from drop-down, which will populate block and then use can enter quarter name and save submit.
Now, 1 possible solution is to include site as FK in quarter and that will solve the problem - but I don't want to do that. I even tried create separate form instances and call it in view and template - but the problem with this solution is that the mandatory field name from site are also displayed.
How can I show the sitename dropdown on quarter form - where on selecting sitename the user is shown corresponding blockname. On click of save button the data for quarter is saved in db (don't have to save site or block data because we already have those entries)
Any suggestion on approach or solution?

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

How to merge two models in django

I have two models with foreign key.
class Ad(models.Model):
town = models.CharField(max_length=30)
owner = models.ForeignKey(SpaUser, on_delete=models.CASCADE) #My foreign key
contact = SpaUser.objects.filter(email= 'owner').values('firstname ') # I want to access SpaUser.firstname to display in django admin
class SpaUser(models.Model):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
firstname = models.CharField(max_length=30, blank=True)
lastname = models.CharField(max_length=30, blank=True)
I use Ad.contact in Ad model to acess SpaUser.firstname in Spauser model but i can't.
Help me please
You can make contact a property instead (and you should make use of the foreign key owner instead of filtering from another queryset of SpaUser):
class Ad(models.Model):
#property
def contact(self):
return self.owner.firstname

how to reference to the django user model

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

Resources