I'am trying to make a queryset in django but i'am without luck.
for some reason my model seems to be wrong.
I'll simplify.
I have this Classes in the models.py:
class RcAnalysis(models.Model):
id = models.AutoField(db_column='Id', primary_key = True) # Field name made lowercase.
/*
some other 10 columns (srry can't post here)
*/
class Meta:
db_table = 'rc_Analysis'
class RcAnalysistag(models.Model):
analysisid = models.ForeignKey(RcAnalysis, db_column='AnalysisId') # Field name made lowercase.
tagid = models.ForeignKey(LabTags, db_column='TagId') # Field name made lowercase.
class Meta:
db_table = 'rc_AnalysisTag'
I need to join the RcAnalysis with analysistag model.
But i dont have a field that i can call RcAnalysisTag proper.
Its like this SQL query:
...
from rc_Analysis A
...
inner join rc_AnalysisTag At on ( A.Id = At.AnalysisId )
inner join lab_Tags T on ( T.Id = At.TagId )
Someone?
Add a related_name="tags" to the foreign key definition. Then you can do:
analysis_object = RCAnalysis.object.get(id=1)
related_tags = analysis_object.tags.all()
Related
I have four models as follows:
class modelA(models.Model):
name = models.CharField(...)
class modelB(models.Model):
date = models.DateTimeField(...)
A = models.ForeignKey(modelA, ...)
class modelC(models.Model):
email = models.CharField(...)
B = models.ForeignKey(modelB, ...)
class modelD(models.Model):
uid = models.CharField(...)
C = models.ForeignKey(modelC)
Given modelA element id, I have to filter modelD elements based on that id. But I am not sure about how to do that.
I appreciate any ideas!
modalD.objects.filter(C__B__A__name ='name')
when you use double underscore you filter the related Inheritance modal
I use django-admin-sortable 2.1.2 and django 1.11.
The problem is that the order is not saving when I try to change it from my admin panel. I think this may be due to already existing model instances.
Here is the part of my current code:
// models.py
class Category(SortableMixin):
name = models.CharField(
_('name'),
max_length=150,
)
order = models.PositiveIntegerField(
default=0,
db_index=True,
)
class Meta:
verbose_name = _('category')
verbose_name_plural = _('categories')
ordering = ['order']
// admin.py
class CategoryAdmin(SortableModelAdmin):
class Meta:
model = Category
fields = (
'name',
)
sortable = 'order'
The default value is set as 0 because of already existing objects. I tried to change their order manually in shell console but it did not help.
I want to avoid deleting my objects and creating them again.
Do you have any ideas how to fix this?
I decided to use another class to inheritance from in my admin.py file.
Instead of:
from suit.admin import SortableModelAdmin
class CategoryAdmin(SortableModelAdmin):
class Meta:
model = Category
fields = (
'name',
)
sortable = 'order'
I use:
from adminsortable.admin import SortableAdmin
class CategoryAdmin(SortableAdmin):
class Meta:
model = Category
fields = (
'name',
)
sortable = 'order'
It works a little different but the effect is satisfying for me and solves my problem.
So I got 4 tables in a MySQL database.
The database is managed with Django under an app I created with Django.
Here are 2 of the 4 classes in the file models.py corresponding to the database tables:
from __future__ import unicode_literals
from django.db import models
class Pdb(models.Model):
id_pdb_chain = models.CharField(db_column='id_PDB_chain', primary_key=True, max_length=5) # Field name made lowercase.
id_pdb = models.CharField(db_column='id_PDB', max_length=4) # Field name made lowercase.
chaine = models.CharField(max_length=10)
header = models.CharField(max_length=255)
sequence_proteine = models.TextField(db_column='sequence_Proteine') # Field name made lowercase.
start_seq = models.IntegerField()
taille_proteine = models.IntegerField(db_column='taille_Proteine') # Field name made lowercase.
resolution_pdb = models.FloatField(db_column='resolution_PDB') # Field name made lowercase.
meth_res = models.ForeignKey('MethodesRes', models.DO_NOTHING, db_column='meth_Res') # Field name made lowercase.
def __unicode__(self):
return self.id_pdb
class Meta:
managed = False
db_table = 'PDB'
class StructSec(models.Model):
id_struct_sec = models.AutoField(primary_key=True)
start_pred = models.IntegerField()
structure_predite = models.TextField(db_column='structure_Predite') # Field name made lowercase.
nombre_ppii = models.IntegerField(db_column='nombre_PPII') # Field name made lowercase.
pourcentage_ppii = models.FloatField(db_column='pourcentage_PPII') # Field name made lowercase.
angle_phi = models.TextField()
angle_psi = models.TextField()
id_pdb_chain = models.ForeignKey(Pdb, models.DO_NOTHING, db_column='id_PDB_chain') # Field name made lowercase.
nom_analyse = models.ForeignKey(MethodesAnalyse, models.DO_NOTHING, db_column='nom_Analyse') # Field name made lowercase.
def __unicode__(self):
return self.structure_predite
class Meta:
managed = False
db_table = 'struct_sec'
As you can see I already found a way to display a field for each table in the admin page with this part in each table:
def __unicode__(self):
return self.structure_predite
But when I want to replace "structure_predite" this by the primary key in the "StructSec" class like this:
def __unicode__(self):
return self.id_struct_sec
Django return this error:
TypeError: coercing to Unicode: need string or buffer, long found
I also have to mention that I have made few modifications in the "admin.py" file here it is:
from django.contrib import admin
from .models import Pdb, MethodesAnalyse, MethodesRes, StructSec
class PdbInline(admin.TabularInline):
model = Pdb
class PdbAdmin(admin.ModelAdmin):
list_display = ('id_pdb','header','chaine','taille_proteine','meth_res')
list_filter = ['chaine','meth_res']
search_fields = ['id_pdb_chain','header']
class MethodesAnalyseInline(admin.TabularInline):
model = MethodesAnalyse
class MethodesAnalyseAdmin(admin.ModelAdmin):
list_display = ('nom_analyse')
class MethodesResInline(admin.TabularInline):
model = MethodesRes
class MethodesResAdmin(admin.ModelAdmin):
list_display = ('meth_res')
class StructSecInline(admin.TabularInline):
model = MethodesRes
class StructSecAdmin(admin.ModelAdmin):
list_display = ('id_struct_sec','nombre_PPII','pourcentage_PPII','id_PDB','nom_Analyse')
search_fields = ['nombre_ppii','pourcentage_ppii']
admin.site.register(Pdb,PdbAdmin)
admin.site.register(MethodesAnalyse)
admin.site.register(MethodesRes)
admin.site.register(StructSec)
Knowing this, my question is simple:
How to display the autoincremented IDs (Primary Key) from the class StructSec in the corresponding admin table without errors?
I think the error is raising due to None value. Python cannot convert None.
Replace your unicode definition to 'str' as:
def __str__(self):
return self.id_struct_sec
Sijan answer is correct, I will just add that, to make links work, you may also have to do this:
def __str__(self):
return str(self.id_struct_sec)
Without the "str()" in the return, links don't work and return errors when clicked.
I'm working now on my first Django project. I want to render results table which contains all fields from Priekabos model and one custom column from Grafikas which should contain something similar to:
SELECT max(kada_moketi) FROM grafikas WHERE priekabos_id = ?
Whatever I try from examples nothing works. Should I write another view function with that custom query:
(Grafikas.objects.filter(priekabos_id=1)
neither with:
.aggregate(Max('kada_moketi')
neither with:
.latest('kada_moketi')
worked for me I created a new table class in tables.py which later PriekabosTable will inherit? That didn't work for me too.
Here's my code:
models.py
class Grafikas(models.Model):
id = models.AutoField(primary_key=True)
mokejimo_nr = models.IntegerField()
kada_moketi = models.DateField()
priekabos = models.ForeignKey('Priekabos', models.DO_NOTHING)
class Priekabos(models.Model):
id = models.AutoField(primary_key=True)
sutarties_nr = models.CharField(unique=True, max_length=45, verbose_name='Sut. Nr.')
nuomos_pradz = models.DateField()
sutarties_trukme = models.IntegerField()
views.py
def priekabos_table(request):
table = PriekabosTable(Priekabos.objects.all())
RequestConfig(request, paginate={'per_page': 20}).configure(table)
return render(request, 'isperkamoji_nuoma/priekabos_table.html', {'table': table})
tables.py
class PriekabosTable(tables.Table):
class Meta:
model = Priekabos
attrs = {"class": "paleblue"}
fields = ('id', 'sutarties_nr', 'nuomos_pradz')
For better understanding, here's 'grafikas' table:
MySQL 'grafikas' table
It sounds like you might be able to fetch the extra field using annotate.
from django.db.models import Max
queryset = Priekabos.objects.annotate(max_kada_moketi=Max('grafikas__kada_moketi'))
table = PriekabosTable(queryset)
Remember to add the field to your table.
class PriekabosTable(tables.Table):
class Meta:
model = Priekabos
attrs = {"class": "paleblue"}
fields = ('id', 'sutarties_nr', 'nuomos_pradz', 'max_kada_moketi')
I have these tables:
class OpeDatos(models.Model):
id_dato = models.IntegerField(primary_key=True)
id_usuario = models.ForeignKey(SisUsuarios, db_column='id_usuario')
id_region = models.ForeignKey(SisRegiones, db_column='id_region')
titulo = models.CharField(max_length=70, blank=True)
class Meta:
managed = False
db_table = 'ope_datos'
class OpeProductos(OpeDatos):
id_producto = models.IntegerField(primary_key=True)
iddato = models.OneToOneField(OpeDatos, primary_key=True, db_column="id_dato", parent_link=True)
id_producto_tipo = models.ForeignKey(DefProductosTipos, db_column='id_producto_tipo')
class Meta:
managed = False
db_table = 'ope_productos'
I want to insert data :
from apps.inicio.models import SisUsuarios, SisRegiones, OpeDatos
usuario = SisUsuarios.objects.get(pk=1)
region = SisRegiones.objects.get(pk=1)
datos = OpeDatos()
datos.id_usuario = usuario
datos.id_region = region
datos.save()
producto = OpeProductos()
producto.iddato = datos.id_dato
producto.save()
displays this message:
ValueError at /productos/add/
Cannot assign None: "OpeProductos.iddato" does not allow null values.
can you help me, please.
When creating an id manually you should use AutoField instead of IntegerField
id_dato = models.AutoField(primary_key=True)
https://docs.djangoproject.com/en/1.6/ref/models/fields/#autofield
What is happening is that since you are not explicitly defining the 'datos' object's id it doesnt have one, and then producto complains because the key can't have an empty value.
AutoField should fix this
I am surprised it doesn't fail at the earlier line: datos.save() because you have not supplied a value for the primary key datos.id_dato
Normally in Django you would need to use an AutoField to get an auto-incrementing primary key.
Also you should not be specifying primary_key=True on the OpeProductos.iddato field, you can only have one primary key per model.
Then the error you are seeing is due to the fact that datos.id_dato is None since you did not provide any value for it before saving the datos instance.