django ratings along with one to one field - django

models.py
class Restaurant(models.Model):
#fields here
class Food(models.Model):
rating = RatingField(range=5, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)
restaurant = models.OneToOneField(Restaurant)
class Service(models.Model):
rating = RatingField(range=5, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)
restaurant = models.OneToOneField(Restaurant)
doubt
how am i suppose to integrate the food and service along with the restaurant model and also be able to rate them aswell , please help , thanks in advance

Instead of:
class Restaurant(models.Model):
#fields here
class Food(models.Model):
rating = RatingField(range=5, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)
restaurant = models.OneToOneField(Restaurant)
class Service(models.Model):
rating = RatingField(range=5, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)
restaurant = models.OneToOneField(Restaurant)
Try:
class Restaurant(models.Model):
#fields here
food_rating = RatingField(range=5, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)
service_rating = RatingField(range=5, weight=5,can_change_vote = True,allow_delete = True,allow_anonymous = True)
KISS

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

How to connect an object automatically with user who is creating it and display those objects only which a specific user has created in django?

I am making a real estate app in django and the problem i am getting is that a user can login in his account and begin creating his properties and then he can view those properties but what i am getting is the properties of every user on page while it should be only the propety that specific user created.
Here,s the models.py of property and i am using the django's user model
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class Property(models.Model):
title = models.CharField(max_length = 210,default = 'None')
STATUS_CHOICES = (
('R','Rent'),
('S','Sale'),
)
status = models.CharField(max_length = 210,choices = STATUS_CHOICES,default = 'None')
price = models.IntegerField(default = 'None')
area = models.CharField(max_length = 210,default = 'None')
ROOM_CHOICES = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('MORE','More'),
)
rooms = models.CharField(max_length = 210,choices = ROOM_CHOICES,default = 'None')
BATHROOM_CHOICES = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
)
bathroom = models.CharField(max_length = 210,choices = BATHROOM_CHOICES,default = 'None')
address = models.CharField(max_length = 210,default = 'None')
state = models.CharField(max_length = 210,default = 'None')
code = models.CharField(max_length = 210,default = 'None')
images = models.ImageField(upload_to = 'media',default = 'None')
info = models.TextField(max_length = 1000,default = 'None')
parking = models.BooleanField(default = False)
air = models.BooleanField(default = False)
swimming = models.BooleanField(default = False)
laundry = models.BooleanField(default = False)
dealer_name = models.CharField(max_length = 210,default = 'None')
dealer_email = models.EmailField(max_length = 210,default = 'None')
dealer_number = models.CharField(max_length = 210,default = 'Not mentioned')
user = models.ForeignKey(User,related_name = 'user')
def get_absolute_url(self,*args,**kwargs):
return reverse('profile_details:property', kwargs={'pk':self.pk,})
Also I want help with some course that can help me go through django completely and clearly so i can encouner these problems in the future.If you know any then please write down in comments.
You got two options to get the properties of a user.
Using the filter() method:
# View to display the user properties
def properties_page(request):
properties = Property.objects.filter(user=request.user)
return render(request, 'app/user_properties.html', {'properties': properties})
Using _set.all()
# View to display the user properties
def properties_page(request):
properties = request.user.property_set.all()
return render(request, 'app/user_properties.html', {'properties': properties})

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

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