I've 2 models
class ShipmentBagSealMapping(models.Model):
bag_seal = models.CharField(max_length = 255)
status = models.CharField(max_length = 255, default = 'open')
time = models.DateTimeField( auto_now_add = True, db_index = True)
shipment_id = models.ForeignKey('Shipment', related_name = 'bags')
class Shipment(models.Model):
job_id = models.CharField(max_length = 255)
time = models.DateTimeField( auto_now_add = True, db_index = True)
I want to write a JOIN query which tells me the count of records in ShipmentBagSealMapping with status = close and time of Shipment is in range [start_time and end_time].
Here' what I tried:
total_bags = ShipmentBagSealMapping.objects.filter(shipments__time__range = [start_time,end_time],status='close').values('bag_seal').distinct().count()
But it throws an error saying :-
Cannot resolve keyword 'shipments' into field. Choices are: bag_seal, id, shipment_id, status, time
How do I do it?
This should do it:
total_bags = ShipmentBagSealMapping.objects.filter(shipment_id__time__range = [start_time,end_time],status='close').values('bag_seal').distinct().count()
See you have defined the field as shipment_id not shipments
Django will automatically add _id in your ForeignKey, so make some change like this may help
class ShipmentBagSealMapping(model.Model):
bag_seal = models.CharField(max_length = 255)
status = models.CharField(max_length = 255 )
time = models.DateTimeField( auto_now_add = True)
shipments = models.ForeignKey('Shipment', related_name = 'bags')
Related
class Mio_terminal(models.Model):
terminal = models.CharField(max_length = 50)
gate = models.CharField(max_length = 50)
gate_status = models.CharField(max_length = 50, default = 'open') #open, occupied, under_maintenance
class Meta:
unique_together = [['terminal', 'gate']]
class Mio_flight_schedule(models.Model):
fact_guid = models.CharField(max_length=64, primary_key=True)
airline_flight_key = models.ForeignKey(Mio_airline, related_name = 'flight_key', on_delete = models.CASCADE)
source = models.CharField(max_length = 100)
destination = models.CharField(max_length = 100)
arrival_departure = models.CharField(max_length=12)
time = models.DateTimeField()
gate_code = models.ForeignKey(Mio_terminal, related_name = 'terminal_gate', null = True, on_delete = models.SET_NULL)
baggage_carousel = models.CharField(max_length = 100)
remarks = models.CharField(max_length = 100)
terminal_code = models.ForeignKey(Mio_terminal, related_name = 'airport_terminal', null = True, on_delete = models.SET_NULL)
These are models for terminal and flight schedules.
enter image description here
enter image description here
I want to have a terminal name and gate code instead of the object ...
I know we can get this by using the str method in models....but we get only a single value for this...not more than one
I want to use the terminal as a foreign_key for terminal_code in the flight_schedule model and the gate as a gate_code.I am getting terminal_code _gate code as a string ...but it's not reflecting as separate entities...I don't want the combined string.....I want when I click on the terminal ...only the terminal dropdown should display..and the same for the gate code
please let me know how should I deal with this.
You can change the display name of models in django admin interface by using def __str__(self).
So for in your code add this function after the Mio_terminal class :
class Mio_terminal(models.Model):
terminal = models.CharField(max_length = 50)
gate = models.CharField(max_length = 50)
gate_status = models.CharField(max_length = 50, default = 'open') #open, occupied, under_maintenance
class Meta:
unique_together = [['terminal', 'gate']]
# add this
def __str__(self):
return str(self.terminal+' '+self.gate)
I have not been able to resolve this IntegrityError issue in my Django's unittest. Here are my models:
class UserProfile(models.Model):
''' UserProfile to separate authentication and profile '''
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True, blank = True)
# Note: first name and last name is in the custom User model
first_name = models.CharField(max_length = 20, blank = True, null = True)
last_name = models.CharField(max_length = 30, blank = True, null = True)
address = models.CharField(max_length = 100, null=True, blank = True)
address_city = models.CharField(max_length = 30, null = True, blank = True)
metropolitan = models.CharField(max_length = 30, null = True, blank = False)
class Municipality(models.Model):
name = models.CharField(max_length = 50)
abb = models.CharField(max_length = 5)
date_created = models.DateTimeField(auto_now_add = True)
date_modified = models.DateTimeField(auto_now = True)
userprofile = models.ForeignKey('user_profile.UserProfile', blank = False, null = False, related_name = 'userprofile_municipalities', on_delete = models.CASCADE)
class Project(models.Model):
name = models.CharField(max_length = 50)
logo = models.ImageField(null=True, blank = True, width_field = 'logo_width', height_field = 'logo_height')
logo_height = models.IntegerField(default = 40)
logo_width = models.IntegerField(default = 40)
date_created = models.DateTimeField(auto_now_add = True )
date_modified = models.DateTimeField(auto_now = True )
# RELATIONSHIPS:
user_profiles = models.ManyToManyField('user_profile.UserProfile', through = 'ProjectAssociation', through_fields = ('project', 'user_profile' ), blank = True, related_name = 'user_projects')
address = models.OneToOneField(Address, on_delete = models.PROTECT, null = True, blank = True)
municipality = models.ForeignKey('development.Municipality', related_name = 'municipality_projects', null = False, blank = False)
class Job(models.Model):
project = models.OneToOneField('project_profile.Project', blank = False, on_delete = models.CASCADE, related_name = 'job')
...
date_modified = models.DateTimeField(auto_now_add = True)
date_created = models.DateTimeField(auto_now = True)
class Invoice(models.Model):
PO = models.CharField(max_length = 50, blank = False, null = False) # e.g. Mixed Use Residential Commercial Rental Invoice
invoice_type = models.CharField(max_length = 40)
date_created = models.DateTimeField(auto_now = True)
date_modified = models.DateTimeField(auto_now_add = True)
job = models.ForeignKey(DevelopmentProject, related_name = 'job_invoices', blank = True, null = True, on_delete = models.CASCADE)
Invoice_creator = models.ForeignKey('user_profile.UserProfile', related_name = 'created_invoices', blank = True, null = True, on_delete = models.SET_NULL) # ModelForm to enforce If the Invoice creator's account is closed, the corresponding Invoices to be preserved
Invoice_reviewer = models.ForeignKey('user_profile.UserProfile', related_name = 'reviewed_invoices', blank = True, null = True , on_delete = models.SET_NULL ) # The reviewer is not necessary, but
...
In my unittest, I am getting integrity error message even when I try to explicitly assign unique id to the created instance:
class UpdateinvoiceTestCase(TestCase):
''' Unit Test for Updateinvoice View '''
def setUp(self):
self.factory = RequestFactory()
# Create the dependencies
self.userprofile = mommy.make('user_profile.UserProfile')
print ('User profile: ', self.userprofile, ' - userprofile id: ', self.userprofile.id )
self.municipality = mommy.make('development.municipality', userprofile = self.userprofile, _quantity=1)
self.project = mommy.make('project_profile.Project', municipality = self.municipality[0], _quantity=2)
self.job = mommy.make('development.Job', project = self.project[0] )
# Create invoice
self.invoice = mommy.make('development.invoice', job = self.job)
# Passing the pk to create the url
the_uri = reverse('development:update_invoice', args=(self.invoice.pk,))
the_url = 'http://localhost:8000' + reverse('development:update_invoice', args=(self.invoice.pk,))
# Creating a client:
self.response = self.client.get(the_url, follow=True)
def test_url(self):
''' Ensure that the url works '''
self.assertEqual(self.response.status_code, 200)
I have made sure only one test is run using so there is no sharing of the data between different testcases that would throw Django off:
python manage.py test project.tests.test_views.UpdateViewTestCase
I get the the following error message:
IntegrityError: duplicate key value violates unique constraint "development_developmentproject_project_id_key"
DETAIL: Key (project_id)=(1) already exists
I also tried using mommy.make to create project, but I got the same error message. I also tried to specifically assign non-existent ids to the Project creation line, but could not convince Django to stop complaining.
So, Project is being created twice, but I cannot figure out why and where. Any help is much appreciated!
It turned out that I've used signals which created an instance already and I was creating the same instance in my setUpTestData again. The solution was to avoid creating a duplicate instance or simply use get_or_create instead of create or mommy.make
I've 3 models.
class ShipmentWeightMapping(models.Model):
id = models.IntegerField(primary_key = True)
weight = models.CharField(max_length = 255)
status = models.CharField(max_length = 255)
time = models.DateTimeField(auto_now = True, auto_now_add = True)
shipment_id = models.ForeignKey('Shipment')
class ShipmentDimensionMapping(models.Model):
id = models.IntegerField(primary_key = True)
status = models.CharField(max_length = 255)
time = models.DateTimeField(auto_now = True, auto_now_add = True)
length = models.IntegerField()
breadth = models.IntegerField()
height = models.IntegerField()
shipment_id = models.ForeignKey('Shipment')
class Shipment(models.Model):
id = models.IntegerField(primary_key = True)
job_id = models.CharField(max_length = 255)
weights = models.ForeignKey('ShipmentWeightMapping')#backref
dimensions = models.ForeignKey('ShipmentDimensionMapping')#backref
time = models.DateTimeField(auto_now = True, auto_now_add = True, db_index = True)
I want to backref weights and dimensions to their respective classes, so that when I query Shipment model for id=1, I should get length, breadth and height from ShipmentDimensionMapping and weight from ShipmentWeightMapping without querying ShipmentDimensionMapping and ShipmentWeightMapping separately.
For eg:- Currently I do like this.
To get Shipment Details for id = 1, I do the following.
dimension_obj = ShipmentDimensionMapping.objects.filter(shipment_id = 1)[0]
length = dimension_obj.length
#similarly for other details in ShipmentDimensionMapping
weight_obj = ShipmentWeightMapping.objects.filter(shipment_id = 1)[0]
weight = weight_obj.weight
#similarly for other details in ShipmentWeightMapping
shipment_obj = Shipment.objects.filter(shipment_id = 1)[0]
job_id = shipment_obj.job_id
#similarly for other details in Shipment
Is there any way in which I only query shipment_obj and I get details of ShipmentWeightMapping and ShipmentDimensionMapping?
Also, I always use the result at zeroth index [0] to get the result. Although the result returned always contains only 1 item, still I need to do [0]. How can I avoid this as well?
Since weight and dimension data are on other tables, you can't get them without querying these two tables.
For the second question, if you know there's only one entry, you can do:
shipment_obj = Shipment.objects.get(id=1)
BTW; you don't have to add ID values explicitly since they are called id in your code as well which is by default in Django.
Can you see why I am getting this model validation error?
I have the table in MySQL called 'paypal_transactions' with records.
I'm trying to copy this project over to another computer with the existing database.
Error Message:
One or more models did not validate: store.purchase: 'paypal_transaction' has a
relation with model <class 'f3.paypal.models.PaypalPaymentTransactions'>, which
has either not been installed or is abstract.
paypal/models.py
class PaypalPaymentTransactions(models.Model):
class Meta:
db_table = 'paypal_transactions'
payment_id = models.CharField(max_length = 50)
payer = models.CharField(max_length = 25)
amount = models.DecimalField(decimal_places = 2, max_digits = 8,
blank = True, default = "0.00")
currency = models.CharField(max_length = 10)
store/models.py
from f3.paypal.models import PaypalPaymentTransactions
class Purchase(models.Model):
user = models.ForeignKey(User, related_name = 'purchase_user')
product = models.ForeignKey(Design)
quantity = models.IntegerField()
paypal_transaction = models.ForeignKey(
PaypalPaymentTransactions,
default = None,
null = True,
blank = True)
This error occurs probably because of a dependency issue:
Try use the ForeignKey like this:
class Purchase(models.Model):
user = models.ForeignKey(User, related_name = 'purchase_user')
product = models.ForeignKey(Design)
quantity = models.IntegerField()
paypal_transaction = models.ForeignKey(
'f3.paypal.PaypalPaymentTransactions',
default = None,
null = True,
blank = True)
I want to get the result in one list using three different models in django. How do i apply join over three models.
class CurrentDomainChecks(models.Model):
domain = models.ForeignKey(Domains)
check_type = models.ForeignKey(CheckType)
check_date = models.DateTimeField(auto_now_add = True, primary_key=True)
check_value = models.CharField(_('check value'), max_length = 2048)
check_passed = models.BooleanField(default = False)
class DomainStatus(models.Model):
domain = models.ForeignKey(Domains)
domain_status_date = models.DateTimeField(auto_now_add=True,null = True, blank = True)
domain_status = models.IntegerField(null = True, blank = True)
class Domains(models.Model):
domain_name = models.CharField(_('domain name'), max_length = 255, unique = True)
verified = models.BooleanField(default = False)
user = models.ForeignKey(User)
date_added = models.DateTimeField(auto_now_add=True,null = True, blank = True)
date_last_changed = models.DateTimeField(auto_now=True,null = True, blank = True)
monitoring_frequency = models.CharField(_('monitoring frequency'), max_length = 20,blank = True,null = True)
def __unicode__(self):
return self.domain_name
Did you read this about JOIN ?
Django: implementing JOIN using Django ORM?
"Lookups that span relationships"