limit_choices_to within Django model - django

I have a project model. This project contains persons (those who are working on the project). I am trying to also make a model for each project person, including any notes they have on the project and % complete on project.
My issue is that I want to filter the individual_person_in_project to only the persons within the corresponding project. I am trying to use
limit_choices_to = {'person_in_project':User}
I want to limit my choices to users who are persons in my Project model.
class Project(models.Model):
project_name = models.CharField(max_length = 120,null = False,blank = False)
project_percent_complete = models.IntegerField(blank = True,null = True, default = 0)
person_in_project = models.ManyToManyField(User,related_name = 'project_person',blank = True)
project_description = models.CharField(max_length = 300,null = True,blank = True)
class Project_Person(models.Model):
corresponding_project = models.ForeignKey(Project,related_name = 'corresponding_project_this_user_is_in',null = False)
individual_person_in_project = models.ForeignKey(User, related_name = 'a_person_within_the_corresponding_project', limit_choices_to = {'person_in_project':User})
percent_complete = models.IntegerField(default = 0)

I left a comment above, but I think this is a better answer, anyhow:
You can use the through option to track extra information on the manytomanyfield, so you get:
class Project(models.Model):
...
person_in_project = models.ManyToManyField(User, related_name='project_person', blank=True, through=ProjectPerson)
The docs explain the rest of the details, but you shouldn't have to handle the limit_choices_to in that case.

Thank you for your help, it was very useful . The most helpful comment was ryanmrubin and the use of through with ManyToManyField to facilitate their relationship I ended up creating a separate class and associating that with a project.
If I need to tie more information into this new class I will certainly use through with the ManyToManyField.
class Project(models.Model):
project_name = models.CharField(max_length = 120,null = False,blank = False)
project_percent_complete = models.IntegerField(blank = True,null = True, default = 0)
project_description = models.CharField(max_length = 300,null = True,blank = True)
people_in_project = models.ManyToManyField(User,blank = True)
class Project_Tasks(models.Model):
description = models.CharField(max_length = 120,blank = True)
percent_complete = models.IntegerField(default = 0)
user = models.OneToOneField(User,unique = True,blank = True, null = True)
project = models.OneToOneField(Project,unique = True, blank = False, null = True)

Related

How to get exact values of the foreignkeys in django admin

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)

How to use update_or_create with defaults argument

I have the model League
class League(models.Model):
league = models.IntegerField(primary_key=True)
league_name = models.CharField(max_length=200)
country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL)
season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season")
season_start = models.DateField(null = True) season_end = models.DateField(null = True)
league_logo = models.URLField(null = True) league_flag = models.URLField(null = True)
standings = models.IntegerField(null=True)
is_current = models.IntegerField(null=True)
I created objects from this model. After it i needed to add some additional fields to League model after adding those fields League object became so
class League(models.Model):
league = models.IntegerField(primary_key=True)
league_name = models.CharField(max_length=200)
country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL)
season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season")
season_start = models.DateField(null = True) season_end = models.DateField(null = True)
league_logo = models.URLField(null = True) league_flag = models.URLField(null = True)
standings = models.IntegerField(null=True)
is_current = models.IntegerField(null=True)
cover_standings = models.BooleanField(null=True)
cover_fixtures_events = models.BooleanField(null=True)
cover_fixtures_lineups = models.BooleanField(null=True)
cover_fixtures_statistics = models.BooleanField(null=True)
cover_fixtures_players_statistics = models.BooleanField(null=True)
cover_players = models.BooleanField(null=True)
cover_topScorers = models.BooleanField(null=True)
cover_predictions = models.BooleanField(null=True)
cover_odds = models.BooleanField(null=True)
lastModified = models.DateTimeField(auto_now=True)
I did migrations and added these fields to db schema. Now i want to add to these added fields values. I read about
update_or_create method and tried to use it for updating League model objects
leagues_json = json.load(leagues_all)
data_json = leagues_json["api"]["leagues"]
for item in data_json:
league_id = item["league_id"]
league_name = item["name"] country_q =Country.objects.get(country = item["country"])
season = Season.objects.get(season = item["season"])
season_start = item["season_start"]
season_end = item["season_end"]
league_logo = item["logo"]
league_flag = item["flag"]
standings = item["standings"]
is_current = item["is_current"]
coverage_standings = item["coverage"]["standings"]
coverage_fixtures_events = item["coverage"]["fixtures"]["events"]
coverage_fixtures_lineups = item["coverage"]["fixtures"]["lineups"]
coverage_fixtures_statistics = item["coverage"]["fixtures"]["statistics"]
coverage_fixtures_plaers_statistics = item["coverage"]["fixtures"]["players_statistics"]
coverage_players = item["coverage"]["players"]
coverage_topScorers = item["coverage"]["topScorers"]
coverage_predictions = item["coverage"]["predictions"]
coverage_odds = item["coverage"]["odds"]
b = League.objects.update_or_create(league = league_id,
league_name = league_name,
country_code = country_q,season = season,
season_start = season_start,
season_end = season_end,
league_logo = league_logo,
league_flag = league_flag,
standings = standings,
is_current = is_current,
cover_standings = coverage_standings,
cover_fixtures_events = coverage_fixtures_events,
cover_fixtures_lineups = coverage_fixtures_lineups,
cover_fixtures_statistics= coverage_fixtures_statistics,
cover_fixtures_players_statistics = coverage_fixtures_players_statistics,
cover_players= coverage_players,
cover_topScorers = coverage_topScorers,
cover_predictions = coverage_predictions,
cover_odds = coverage_odds)
While i am trying to update objects by above method i get an error
django.db.utils.IntegrityError: duplicate key value violates unique constraint "dataflow_league_pkey"
DETAIL: Key (league)=(1) already exists.
I read about defaults argument of update_or_create method but didn't understand how to useit in my case. Can anyone help me
If you use update_or_create like this, first of all, your code will search the row in db with that all parameters.
I think you want to search league by league id and it works like this
You create the dict by any way of defaults, I just copy your code
defaults = dict(
league_name=league_name,
country_code=country_q,
season=season,
season_start=season_start,
season_end=season_end,
league_logo=league_logo,
league_flag=league_flag,
standings=standings,
is_current=is_current,
cover_standings=coverage_standings,
cover_fixtures_events=coverage_fixtures_events,
cover_fixtures_lineups=coverage_fixtures_lineups,
cover_fixtures_statistics=coverage_fixtures_statistics,
cover_fixtures_players_statistics=coverage_fixtures_players_statistics,
cover_players=coverage_players,
cover_topScorers=coverage_topScorers,
cover_predictions=coverage_predictions,
cover_odds=coverage_odds)
And use this defaults to update or create league with particular id
League.objects.update_or_create(defaults=defaults, league=league_id)
This code will find league with league_id and update it with data which you passed as the defaults parameter
OR
This code will create new league with that id and these params
You can use update_or_create like this
if exist, it return obj and created false
if not exist, it return obj and created true.
obj, created = League.objects.update_or_create(defaults=defaults, league=league_id)

Django Testing IntegrityError: duplicate key value violates unique constraint DETAIL: Key (project_id)=(1023044) already exists

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

Django Model Won't Validate or Not Installed

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)

Join over django models

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"