Have a model with two classes
class Employee(models.Model):
emp_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
phone_number = models.CharField(max_length=20, unique=True)
company = models.ForeignKey(Company, db_column='company_id')
class Company(models.Model):
company_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=150)
phonenumber = models.CharField(max_length=20, unique=True)
in my views.py i have a method that receive a post request and does registers an employee using get_or_create like so
employee, created = Employee.objects.get_or_create(name=emp_name, phone_number=emp_phone_number,company_id=emp_company_id)
employee.save()
but get_or_create results in an error
Cannot resolve keyword 'company_id' into field. Choices are:name,phone_number,company
how do i save the company_id as reference key?
Try:
company = Company.objects.get(id=company_id)
employee, created = Employee.objects.get_or_create(name=emp_name, phone_number=emp_phone_number,company=company)
employee.save()
Related
I have four models in my django application with following structure:
class User(models.Model):
first_name = models.CharField()
last_name = models.CharField()
class Customer(models.Model):
kyc_record = models.ForeignKey(CustomerKYCRecord, on_delete=models.CASCADE,null=True,default=None)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class SomeItem(models.Model):
price = models.DecimalField()
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
class SomeOtherItem(models.Model):
transaction_status = models.CharField(max_length=200, default='INITIATED')
some_item = models.ForeignKey(SomeItem, on_delete=models.CASCADE, unique=True)
I have to create an API and I have been given a list of SomeItem. I have to write a django queryset line to extract first_name and last_name from User model, all details of SomeItem model and all details of SomeOtherItem model(if present).
I also have to create a serializer to parse the data as a Python dict.
Will be great if one can help me in this.
Models.py
from django.db import models
class BusinessType(models.Model):
method = models.CharField(max_length=25)
class Vendor(models.Model):
first_name = models.CharField(max_length=25)
middle_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
nick_name = models.CharField(max_length=10)
email = models.CharField(max_length=30)
company = models.CharField(max_length=25)
phone = models.CharField(max_length=15)
mobile = models.CharField(max_length=10)
fax = models.CharField(max_length=10)
billing_address_street = models.CharField(max_length=120)
billing_address_city = models.CharField(max_length=20)
billing_address_state = models.CharField(max_length=20)
billing_address_zip = models.CharField(max_length=6)
billing_address_country = models.CharField(max_length=20)
shipping_address_street = models.CharField(max_length=120)
shipping_address_city = models.CharField(max_length=20)
shipping_address_state = models.CharField(max_length=20)
shipping_address_zip = models.CharField(max_length=6)
shipping_address_country = models.CharField(max_length=20)
notes = models.CharField(max_length=120)
gstin = models.CharField(max_length=25, null=True)
tin = models.CharField(max_length=25, null=True)
business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE)
Serializers.py
from rest_framework import serializers
from .models import Vendor,BusinessType
class BusinessTypeSerializer(serializers.HyperlinkedModelSerializer):
[enter image description here][1]
class Meta:
model = BusinessType
fields = ('id','method')
class VendorSerializer(serializers.HyperlinkedModelSerializer):
business_type = serializers.CharField(source='business_type.method')
class Meta:
model = Vendor
fields = ('id','first_name','middle_name','last_name','nick_name','email','company','phone','mobile','fax','billing_address_street','billing_address_city','billing_address_state','billing_address_zip','billing_address_country','shipping_address_street','shipping_address_city','shipping_address_state','shipping_address_zip','shipping_address_country','notes','gstin','tin','business_type')
In Django restframework, foreign key value is not getting in HyperlinkedModelserializer in 'business_type' field. When I tried to post method after declaring foreign key field, it says:
"AssertionError: The .create() method does not support nested
writable fields by default. Write an explicit .create() method for
serializer UserSerializer, or set read_only=True"
I'm trying to make the following models in django:
class Client(models.Model):
client = models.CharField(max_length=200)
loyal = models.BooleanField(default=False)
class Contact(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
client_id = models.ForeignKey(Client, on_delete=models.SET_NULL,null=True)
class Activity(models.Model):
title = models.CharField(max_length=30)
text = models.CharField(max_length=1000)
client_id = models.ForeignKey(Client, on_delete=models.PROTECT)
contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT,limit_choices_to={'id__in': client_id.contact_set.all().values('id').query})
What i want to achieve - when i creating an activity and choose client in it - i want that in contact field i have to choose only from the contacts which related to choosen client, because when i do:
contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT)
Django allow me to choose from all the contacts. I want to limit somehow the list of contacts from i need to choose, i try this way:
contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT,limit_choices_to={'id__in': client_id.contact_set.all().values('id').query})
But i receive this error:
AttributeError: 'ForeignKey' object has no attribute 'contact_set'
How should i do it right?
I really can't figure out why I can't point by Foregin Key the exactly same id multiple times.
I'm trying to use Django ORM to the database that already exists.
And it looks like this:
I wanted to create model according to that:
class TestID(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=250)
test_case_id = models.CharField(max_length=250, unique=True)
module = models.CharField(max_length=50)
full_description = models.TextField()
class Meta:
db_table = "TestID"
class TestCaseRun(models.Model):
id = models.AutoField(primary_key=True)
soft_version = models.CharField(max_length=50)
automated_test_case_version = models.CharField(max_length=50, unique=True)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
checksum = models.CharField(max_length=250)
result = models.CharField(max_length=50)
test_case_id = models.ForeignKey(TestID, db_column='test_case_id')
class Meta:
db_table = "TestCaseRun"
class TestStep(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=250, null=False)
result = models.CharField(max_length=50)
description = models.CharField(max_length=250)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
test_case = models.ForeignKey(TestCaseRun, db_column='id')
class Meta:
db_table = "TestStep"
class single_check(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=250)
comparison = models.CharField(max_length=5, null=False)
expected = models.CharField(max_length=50, null=False)
actual = models.CharField(max_length=50, null=False)
result = models.CharField(max_length=50)
comment = models.CharField(max_length=250)
event_time = models.DateTimeField()
test_step_id = models.ForeignKey(TestStep, db_column='id')
class Meta:
db_table = "single_check"
class action(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=250)
type = models.CharField(max_length=5, null=False)
result = models.CharField(max_length=50)
comment = models.CharField(max_length=250)
event_time = models.DateTimeField()
test_step_id = models.ForeignKey(TestStep, db_column='id')
class Meta:
db_table = "action"
class logs(models.Model):
id = models.AutoField(primary_key=True)
msg = models.CharField(max_length=350)
type = models.CharField(max_length=5, null=False)
result = models.CharField(max_length=50)
comment = models.CharField(max_length=250)
event_time = models.DateTimeField()
test_step_id = models.ForeignKey(TestStep, db_column='id')
class Meta:
db_table = "logs"
When I try to run that code I get errors:
ERRORS:
web_report.TestStep: (models.E007) Field 'test_case' has column name 'id' that is used by another field.
HINT: Specify a 'db_column' for the field.
web_report.action: (models.E007) Field 'test_step_id' has column name 'id' that is used by another field.
HINT: Specify a 'db_column' for the field.
web_report.logs: (models.E007) Field 'test_step_id' has column name 'id' that is used by another field.
HINT: Specify a 'db_column' for the field.
web_report.single_check: (models.E007) Field 'test_step_id' has column name 'id' that is used by another field.
HINT: Specify a 'db_column' for the field.
And I really can not figure out why I can't point by Foregin Key the exactly same id multiple times. Imho nothing is wrong with this design. But I'm beginner in relational database design.
It looks like you are using the db_column argument incorrectly. This is the field on the model that you are linking from, not the column on the model that you are linking to. You cannot use db_column='id', because there is already a primary key id for each model.
Taking your TestStep model as an example:
class TestStep(models.Model):
id = models.AutoField(primary_key=True)
...
test_case = models.ForeignKey(TestCaseRun, db_column='id')
Your diagram shows that it is the test_case_id column that links to the TestCase model. So you should have:
test_case = models.ForeignKey(TestCaseRun, db_column='test_case_id')
or because that is the default, simply
test_case = models.ForeignKey(TestCaseRun)
I've tried reading the docs and previous answers to this question without much luck.
I've got a bunch of student-course registrations and I'd like to see some of those selected registrations in conjunction with some of the attributes of the students. No luck so far...I'd request your advice!
Here's the model:
class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
netID = models.CharField(max_length=8)
class Registration(models.Model):
student = models.ForeignKey(Student)
course = models.ForeignKey(Course)
attendance_M = models.BooleanField(default=False)
attendance_Tu = models.BooleanField(default=False)
and here is the tables.py:
class AttendanceTable(tables.Table):
netID = tables.Column(accessor='Student.netID')
first = tables.Column(accessor='Student.first_name')
last = tables.Column(accessor='Student.last_name')
class Meta:
model = Registration
attrs = {"class": "paleblue"}
fields = ('attendance_M', 'attendance_Tu',)
sequence = ('netID', 'first', 'last', 'attendance_M', 'attendance_Tu',)
While I'm getting data on the attendance values, there's nothing from the student foreign columns.
netID First Last Attendance M Attendance Tu
— — — ✔ ✘
And it's the same deal if I start the Table with model = Student and use accessors against the Registration table, it's the same deal.
I feel like I'm missing something very conceptual and crucial -- please guide me!
The model name in the accessor parameter of the column should be lowercase.
Use accessor='student.netID' instead of accessor='Student.netID'.
When using the accessor parameter, you have to use the field name stated in the Model that has the foreign key, and then select which field from that table you want to use.
So, for these models:
#models.py
class Description_M(models.Model):
id_hash = models.CharField(db_column='Id_hash', primary_key=True, max_length=22)
description = models.CharField(db_column='Description', max_length=255, blank=True, null=True)
class GeoCodes(models.Model):
geo = models.CharField(db_column='Geo', primary_key=True, max_length=5)
city_name = models.CharField(db_column='City', max_length=150, blank=True, null=True)
class RefSources(models.Model):
id_source = models.IntegerField(db_column='Id_source', primary_key=True,)
source_name = models.CharField(db_column='Source', max_length=150, blank=True, null=True)
class Price(models.Model):
id_hash = models.ForeignKey(Description_M, models.DO_NOTHING, db_column='Id_hash')
date= models.ForeignKey(DateTime, models.DO_NOTHING, db_column='Date')
geo = models.ForeignKey(GeoCodes, models.DO_NOTHING, db_column='Geo')
id_source = models.ForeignKey(RefSources, models.DO_NOTHING, db_column='Id_source') # Field name made lowercase.
price = models.FloatField(db_column='Price',primary_key=True, unique=False,default=None)
When using the foreign key to pull fields from that table, you have to:
class price_table(tables.Table):
description = tables.Column(accessor = 'id_hash.description')
city = tables.Column(accessor = 'geo.city_name')
source = tables.Column(accessor = 'id_source.source_name')
class Meta:
model = Price
fields = ['date','price']
sequence = ['description ','date','city ','source','price']
template_name = 'django_tables2/bootstrap.html'