Django insert model foreign key - django

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()

Related

Django ORM query for filtering product price between two number is not working properly

class Product(models.Model):
product_name = models.CharField(max_length=255,unique=True)
slug = models.SlugField(max_length=255)
brand = models.CharField(max_length=255)
price = models.CharField(max_length=255)
product_image_1 = models.ImageField(upload_to = 'photos/product',blank = False)
product_image_2 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_3 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_4 = models.ImageField(upload_to = 'photos/product',blank = False)
product_description = models.TextField()
category_id = models.ForeignKey(Categories,on_delete=models.CASCADE)
subcategory_id = models.ForeignKey(SubCategories, on_delete=models.CASCADE)
stock = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.product_name
def get_url(self):
return reverse('product_detail',args = [self.category_id.slug , self.subcategory_id.slug,
self.slug ])
'''view'''
val=request.POST.get('value')
val = re.findall("\d+", val) # code to get all inigers from string
min_price = int(val[0])
max_price = int(val[1])
print(min_price)
print(max_price)
***product = Product.objects.filter(category_id = categories,is_active =
True,price__gte = min_price, price__lte = max_price)***
when i give value greater than max_value product object returns null object
I want all objects between the two min_value and max_value

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))
)

filter on related_set in Django query

class Hardware(models.Model):
date = models.PositiveSmallIntegerField()
node = models.ForeignKey('Node', on_delete=models.CASCADE,null = True)
slot = models.PositiveSmallIntegerField(null = True)
server = models.CharField(max_length=20,null = True)
server_state = models.CharField(max_length=20,null = True)
adapter = models.CharField(max_length=20,null = True)
adapter_state = models.CharField(max_length=20,null = True)
class Meta:
unique_together = ('date', 'node','slot')
order_with_respect_to = 'node'
def __str__(self):
return self.node.name +" " + self.server
class Node(models.Model):
name = models.CharField(max_length = 40, primary_key = True)
def __str__(self):
return self.name
def inventory_by_node(request):
day = (arrow.now().day) - 1
nodes = Node.objects.prefetch_related("hardware_set").all()
return render(request, 'automation/inventory_by_node.html',{'nodes':nodes})
I need to filter hardware_set based on date which is equal to currrent day. I tried
nodes = Node.objects.prefetch_related(Prefetch("hardwares", quesryset=Hardware.objects.filter(date=day)).all()
but It didn't works says no Pretch is defined
Try this:
prefetch = Prefetch("hardware_set", queryset=Hardware.objects.filter(date=day))
nodes = Node.objects.prefetch_related(prefetch).all()

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"

Get all object from Django ForeignKey Field

I have two models, an Event and a suggestedName. suggestedName has a ForeignKey relationship with Event as well as a IntegerField called 'votes'. I want to get the top 5 suggestedNames associated with an Event.
My models:
class Event(models.Model):
def __unicode__(self):
return unicode(self.id)
id = models.BigIntegerField(blank = 'TRUE', primary_key='TRUE')
version = models.IntegerField(default = 0)
views = models.IntegerField(default = 0)
created = models.DateTimeField(editable = False)
modified = models.DateTimeField()
trained = models.BooleanField(default = False)
type = models.SmallIntegerField(default = 0)
class suggestedName(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
votes = models.IntegerField(default = 0)
event = models.ForeignKey(Event)
What I have in my view is this:
e = Event.objects.get(pk=event_id)
suggestedN = e.suggestedName_set.order_by('votes')[:5].reverse()
But I'm not getting any results.
Try:
e.suggestedname_set.order_by('-votes')[:5]
Or specify a related name
class suggestedName(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=200, blank = True, null = True)
votes = models.IntegerField(default = 0)
event = models.ForeignKey(Event, related_name='suggestions')
and then,
e.suggestions.order_by('-votes')[:5]