How to use update_or_create with defaults argument - django

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)

Related

Filter queryset for foreign key

I need to filter the books associated with my serie model
My models.py
class Serie(models.Model):
serie = models.CharField(max_length = 255)
author = models.ForeignKey(Author, on_delete = models.CASCADE, null = True)
slug = AutoSlugField(populate_from = 'serie', always_update = True)
class Book(models.Model):
serie = models.ForeignKey(Serie, on_delete = models.CASCADE, null = True)
serie_slug = AutoSlugField(populate_from = 'serie', always_update = True, null = True)
book_title = models.CharField(max_length=200)
slug = AutoSlugField(populate_from = 'book_title', always_update = True, null = True)
resume = RichTextField()
pub_date = models.DateTimeField(auto_now_add = True, null = True)
My views.py
class index(ListView):
model = Serie
template_name = 'serie_book_list.html'
ordering = ['id']
def get_queryset(self, *args, **kwargs):
context = super().get_queryset(*args, **kwargs)
search = self.request.GET.get('buscar', None)
if search:
context = context.filter(
Q(serie__icontains = search) |
Q(author__name__icontains = search) |
Q(Book.objects.filter(book_title__icontains = search))
)
return context
I tried to use this code Q(Book.objects.filter(book_title__icontains = search)), but without success.
Cannot filter against a non-conditional expression.
your filter Q(Book.objects.filter(book_title__icontains = search)) not match any field in Serie
try this:
context = context.filter(
Q(serie__icontains=search) |
Q(author__name__icontains=search) |
Q(book__book_title__icontains=search))
)

How to write equivalent filter in django for the below query

Below is a query which I am using for a search screen. Mobile1, sponsor1 and status1 are the field inputs from the user. If these fields are not entered then all the values should be returned as output.
Query:
Select * from customer
where mobile = nvl(mobile1,mobile)
and sponsor = nvl(sponsor1,sponsor)
and status = nvl(status1,status);
Models.py
class customer(models.Model):
company = models.CharField(max_length=3)
mobile = models.CharField(max_length=10)
name = models.CharField(max_length=100)
sponsor = models.CharField(max_length=10)
address1 = models.CharField(max_length=200)
country = models.CharField(max_length=101)
state = models.CharField(max_length=100)
city = models.CharField(max_length=100)
zip = models.CharField(max_length=6)
email = models.EmailField(max_length=100)
status = models.CharField(max_length=1)
creator = models.CharField(max_length=20)
cretime = models.DateTimeField(default=datetime.now)
updator = models.CharField(max_length=20)
updtime = models.DateTimeField(default=datetime.now, blank = True )
Just avoid to specify your filtering condition if the user doesn't enter those values.
For instance:
customers = customer.objects.all()
if mobile1:
customers = customers.filter(mobile=mobile1)
if sponsor1:
customers = customers.filter(sponsor=sponsor1)
# ...
Note that only in the first line I used the model (customer) directly, after that I always reused the queryset (customers), as you can refine your query in multiple steps.
# This worked
name1 = str(request.GET.get('nam'))
mobile1 = str(request.GET.get('mob'))
sponsor1 = str(request.GET.get('spo'))
status1 = str(request.GET.get('stat'))
if (name1 is not None and name1 != ''):
customers_list = customers_list.filter(name=name1)
if (mobile1 is not None and mobile1 != ''):
customers_list = customers_list.filter(mobile=mobile1)
if (sponsor1 is not None and sponsor1 != ''):
customers_list = customers_list.filter(sponsor=sponsor1)
if (status1 is not None and status1 != ''):
customers_list = customers_list.filter(status=status1)
ctx = {'customer': customers_list}
return render(request, 'pages/customer_view.html', ctx)

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 insert model foreign key

Hi I'm trying to populate my django app with data from a dbf file , I'm trying to make objects , as taught in the djangobook
>>> p = Publisher(name='Apress',
address='2855 Telegraph Ave.',
city='Berkeley',
state_province='CA',
country='U.S.A.',
website='http://www.apress.com/')
>>> p.save()
How can I add foreign keys and many to many keys this way ?
Or probably a better approach? dbf files have thousands of rows , so updating data by hand wouldn't be a viable approach.
Here's my models.py as suggested , almoust every model includes a foreign key , or a many to many field , I'm kind of stuck , because of filling them , I'm using dbf2py library to read the foxpro databases, and want to make a script for exporting the data
thanks in advance
from __future__ import unicode_literals
from django.db import models
class Terminos_pago(models.Model):
terminos = models.CharField(max_length = 20)
def __unicode__(self):
return self.terminos
class Clientes(models.Model):
"""docstring for Clientes"""
nombre = models.CharField(max_length=40)
direccion = models.CharField(max_length=70)
estado = models.CharField(max_length=16)
ciudad = models.CharField(max_length=30)
cp = models.IntegerField()
kilometros= models.IntegerField()
rfc = models.CharField(max_length=13 , null = True)
horas = models.DecimalField(null = True,decimal_places = 2 , max_digits = 5)
terminos_pago = models.ForeignKey(Terminos_pago,null=True)
dias_de_credito = models.IntegerField(blank = True , null = True)
def __unicode__(self):
return u'%s %s' % (self.nombre , self.horas)
class Contactos(models.Model):
"""docstring for Contactos"""
nombre = models.CharField(max_length=30)
departamento = models.CharField(max_length=16)
telefono = models.CharField(max_length = 16)
extension = models.IntegerField()
email = models.EmailField(blank = True)
cliente = models.ForeignKey(Clientes)
def __unicode__(self):
return self.nombre
class Maquinas(models.Model):
"""docstring for Maquinas"""
contacto = models.ForeignKey(Contactos , null = True)
id_usuario = models.CharField(max_length=13 , null = True , blank = True)
fabricante = models.CharField(max_length=15 )
no_serie = models.CharField(max_length=10 )
modelo = models.CharField(max_length=10 )
rango_x = models.IntegerField()
rango_y = models.IntegerField()
rango_z = models.IntegerField()
mppl = models.IntegerField()
mppe = models.IntegerField()
probe_type = models.CharField(max_length=10 )
probe_head = models.CharField(max_length=16)
probe_serial = models.CharField(max_length=15 )
extension = models.IntegerField( blank = True , null = True)
version_software=models.CharField(max_length=15)
version_firmware=models.CharField(max_length=15)
controlador = models.CharField(max_length=10)
accesorios = models.CharField(max_length=15 , null = True , blank = True)
driver_software= models.CharField(max_length=15)
modelo_computadora=models.CharField(max_length=10)
fecha_fabricacion = models.DateField(blank=True , null = True)
diametro_stylus= models.IntegerField()
def __unicode__(self):
return u'%s %s %s %s ' % (self.modelo , self.fabricante , self.contacto.nombre , self.contacto.cliente.nombre)
class Servicios(models.Model):
"""docstring for Servicios"""
servicio = models.CharField(max_length = 20)
def __unicode__(self):
return self.servicio
class ListaPrecios(models.Model):
"""docstring for ListaPrecios"""
fecha = models.DateField(null = True)
horas = models.IntegerField()
horas_extra = models.IntegerField()
horas_viaje = models.IntegerField(null = True)
kilometros = models.IntegerField()
hotel = models.IntegerField()
manuales = models.IntegerField()
traslados = models.IntegerField()
avion = models.IntegerField()
sobre_equipaje = models.IntegerField()
renta_auto = models.IntegerField()
papeleria = models.IntegerField()
def __unicode__(self):
return str(self.fecha)
class Ingenieros(models.Model):
"""docstring for Ingenieros"""
nombre = models.CharField(max_length=20)
referencia = models.CharField(max_length=4)
telefono = models.CharField(max_length = 16)
email = models.EmailField(null = True)
def __unicode__(self):
return self.nombre
class Cotizacion(models.Model):
"""docstring for Cotizacion"""
fecha = models.DateField()
contacto = models.ForeignKey(Contactos , null = True)
servicio = models.ManyToManyField(Servicios)
maquinas = models.ManyToManyField(Maquinas)
horas = models.IntegerField()
horas_extra = models.IntegerField(blank=True ,null = True)
#horas_viaje = models.IntegerField()
viajes = models.IntegerField()
hotel = models.IntegerField(blank=True ,null = True)
manuales = models.IntegerField(blank=True ,null = True)
traslados = models.IntegerField( blank=True ,null = True)
aviones = models.IntegerField(blank=True ,null = True)
sobre_equipaje = models.IntegerField(blank=True ,null = True)
renta_auto = models.IntegerField(blank=True ,null = True)
papeleria = models.IntegerField(blank=True ,null = True)
importe = models.IntegerField(blank = True , null = True)
iva = models.DecimalField(decimal_places = 2 , max_digits = 5 ,blank = True , default = 0.16)
observaciones = models.CharField(blank=True ,max_length = 255, null = True)
SA = models.NullBooleanField()
tipo_cambio = models.DecimalField(decimal_places = 2 , max_digits = 5, blank = True , null = True)
def __unicode__(self):
return u'%s %s %s %s' % (self.fecha , self.contacto.cliente.nombre , self.contacto.nombre ,self.servicio)
class Ordenes_de_servicio(models.Model):
"""docstring for Ordenes_de_trabajo"""
fecha = models.DateField(null = True)
ingeniero = models.ManyToManyField(Ingenieros)
observaciones = models.CharField(max_length = 255,null = True , blank = True)
viaticos = models.IntegerField()
orden_compra = models.CharField(max_length = 15)
orden_compra_interna = models.IntegerField(blank = True , null = True)
fecha_servicio = models.DateField(null = True)
viaticos_pagados = models.NullBooleanField()
cotizacion = models.ForeignKey(Cotizacion,null = True)
mail_enviado = models.IntegerField(null=True,blank=True,default=0)
fecha_mail_enviado = models.DateField(null=True , blank = True)
contacto_servicio = models.ForeignKey(Contactos , null = True )
def __unicode__(self):
return u'%s %s' % (self.fecha,self.ingeniero)
class Factura(models.Model):
"""docstring for Factura"""
fecha = models.DateField()
orden_servicio = models.ForeignKey(Ordenes_de_servicio)
descripcion = models.CharField(max_length=255,null = True , blank = True)
pagada = models.NullBooleanField()
def __unicode__(self):
return u'%s %s %s' % (self.orden_servicio.cotizacion.contacto.cliente.nombre , self.orden_servicio , self.fecha)
try and include your models.py, while you do that take a look at One-toMany for Many-to-many relationship
When you define a relationship in a model (i.e., a ForeignKey, OneToOneField, or ManyToManyField), instances of that model will have a convenient API to access the related object(s).
Using the models for example, an Entry object e can get its associated Blog object by accessing the blog attribute: e.blog.
(Behind the scenes, this functionality is implemented by Python descriptors. This shouldn’t really matter to you)
Django also creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Blog object b has access to a list of all related Entry objects via the entry_set attribute: b.entry_set.all().
This is directly from the link i gave above, so visit the link and read deep
If a model has a ForeignKey, instances of that model will have access to the related (foreign) object via a simple attribute of the model.
Example:
>>> e = Entry.objects.get(id=2)
>>> e.blog # Returns the related Blog object.
You can get and set via a foreign-key attribute. As you may expect, changes to the foreign key aren’t saved to the database until you call save(). Example:
>>> e = Entry.objects.get(id=2)
>>> e.blog = some_blog
>>> e.save()

why would my databse entries be coming up empty?

I'm trying to create new instances based off of the form below however when it saves, the database only saves the foreign key value and the order value but nothing else. Any Idea why?
models:
class danceType(models.Model):
eventtype = models.ForeignKey(compType)
dance_name = models.CharField(max_length = 20)
Price = models.FloatField(max_length = 7, null=True, blank=True )
field_2 = models.CharField(max_length = 20, null=True, blank=True)
def __unicode__(self):
fields = ('field_2')
return self.dance_name
class dancer(models.Model):
dancetype = models.ForeignKey(danceType)
e_number = models.IntegerField(max_length = 4, null=True, blank=True)
D1_first_name = models.CharField(max_length = 20)
D1_last_name = models.CharField(max_length = 20)
D1_email = models.EmailField(max_length = 20)
city = models.CharField(max_length = 20)
order = models.PositiveIntegerField()
perform = models.NullBooleanField(null=True, blank=True)
View:
if request.method =='POST':
sub_type = request.POST.get("form")
dancetype = request.POST.get("dancetype")
ext = request.POST.get("quantity")
form = modelformset_factory(dancer, form=CompReg, extra=int(ext))
productform = form(queryset = dancer.objects.none())
if sub_type == "submitted":
productform = form(request.POST, request.FILES)
if productform.is_valid():
for p in productform:
dance=p.save(commit=False)
dance.dancetype_id = 4
dance.order = 1
dance.save()
else:
der = "it didnt save"