Reputation: 41
I am trying to make a query that returns the data of a foreignkey relationship, but I do not succeed. I want to bring the data of the web field of the Radio model to the query that I make of the model ProgramasRadiales. I only manage to bring the data from the Model ProgramasRadiales.
Models
class Radio(models.Model):
usuario = models.ManyToManyField(settings.AUTH_USER_MODEL)
radio = models.CharField('Nombre de la Emisora', max_length=50)
web = models.URLField()
class Meta:
ordering = ['radio']
verbose_name_plural = 'radios'
def __str__(self):
return self.radio
class ProgramasRadiales(models.Model):
rango = (
('lun', 'Lunes'),
('mar', 'Martes'),
('mie', 'Miercoles'),
('jue', 'Jueves'),
('vie', 'Viernes'),
('sab', 'Sábado'),
('dom', 'Domingo')
)
nombre = models.CharField('Nombre del programa de radio', max_length=60)
dias = MultiSelectField('Selecciona los días', choices = rango, max_length=40)
inicio = models.TimeField(blank = False, null = True)
duracion = models.PositiveSmallIntegerField('Duración del programa(minutos)', default=False)
radios = models.ForeignKey(Radio)
class Meta:
ordering = ['nombre']
verbose_name_plural = 'programas radiales'
def __str__(self):
return self.nombre
Querys
datos = ProgramasRadiales.objects.all().values()
<QuerySet [{'nombre': 'Matinal', 'inicio': datetime.time(10, 0), 'radios_id': 2, 'dias': ['mie'], 'duracion': 20, 'id': 3}, {'nombre': 'Nocturnos', 'inicio': datetime.time(18, 0), 'radios_id': 1, 'dias': ['jue', 'vie'], 'duracion': 20, 'id': 4}, {'nombre': 'Siempre Informados', 'inicio': datetime.time(6, 0), 'radios_id': 1, 'dias': ['lun', 'mie', 'vie'], 'duracion': 15, 'id': 2}, {'nombre': 'Tus noticias', 'inicio': datetime.time(7, 0), 'radios_id': 2, 'dias': ['lun', 'mar', 'mie', 'jue', 'vie'], 'duracion': 20, 'id': 1}]>
Upvotes: 0
Views: 959
Reputation: 14391
You will need to use '__' (double underscore operator) to get data of foreign key.
ProgramasRadiales.objects.all().values(
'nombre', 'inicio', 'radios__radio', 'radios__web')
Upvotes: 1
Reputation: 3130
You will need to use select_related
on your query:
https://docs.djangoproject.com/en/1.11/ref/models/querysets/#select-related
datos = ProgramasRadiales.objects.select_related("radios").all()
Upvotes: 1