django get distinct foreignkeys from queryset - mysql

I have a big django MySQL database and im struggling to get this to work efficiently :
models.py :
class Category(models.Model)
name = models.CharField()
class Article(models.Model)
start_date = models.DateTimeField(...)
end_date = models.DateTimeField(...)
active = models.BooleanField(...)
categories = models.ManyToManyField( Category )
I'd like to get all the active categories based on Article queryset. I actually do it this way :
actives_articles = Articles.objects.filter(start_date__gt = datetime.datetime.today(), end_date__lt = another_date, active = True)
actives_categories = Category.objects.filter(article__in = actives_articles).distinct().order_by('name')
actives_articles return about 50k results so this is not efficient at all.
Any idea or pointers ?
Thanks !

I finally got something working with this :
now = datetime.datetime.now()
filters = {
'article__active': True,
'article__start_date__lte':now,
'article__end_date__gte':now,
}
categs = Category.objects.filter(**filters).distinct()
silly me and thanks Django !

Related

Multiple tables with node mysql-model?

I'm working on a project where I use mysql-model and I don't really understand how models work when we have multiple tables.
I have some code on my model user.js:
var mysqlcon = require('../models/db_connexion');
var User_model = mysqlcon.extend({
tableName: "users"
});
var log_user = new User_model();
Some code ...
Then a function to find the user's role:
module.exports.findUserRole = function(userId,callback){
let findUserRoleId = "SELECT role_id FROM users WHERE id = "+userId;
log_user.query(findUserRoleId,function(err,rows,fields){
let role_id = rows[0].role_id;
let findRolesInfo = "SELECT role_name,role_power FROM roles WHERE role_id = " + role_id;
log_user.query(findRolesInfo,callback)
})
And when I call this function, it returns me what I want, but I don't understand why.
My User_model isn't normally using only the table "users" ? So why can I also access to the table "roles" ?
I've searched on the npm documentation and googled it, but didn't found anything, or I missed it.
Thanks for your explanation.
And sorry if I missed something with the presentation, that's my first post.

Bug when trying to fill Many2many or One2many list in odoo v8

Since yesterday I'm facing a weird problem.I'm trying to add all the product category list to a contact at creation time.It's not working neither for a one2many/many2one relation or many2many/many2many relation. I always end up with an empty list of categories in the contact.
class product_category(models.Model):
_inherit = "product.category"
contacts = fields.Many2many('res.partner')
class odepoContact(models.Model):
_inherit = "res.partner"
categs = fields.Many2many('product.category')
#api.model
def create(self, values):
## Here categ is a list containing category ids.
categs = self.env['product.category'].search([])
# values['categs'] = (4,0,categs) Not working =>EMPTY
# values['categs'] = categs Not working =>EMPTY
# values['categs'] = (6,0,categs) Not working =>EMPTY
id = super(odepoContact, self).create(values)
_logger.error(id.categs)
return id
LOG:v8dev openerp.addons.org_chart_dept.org_chart: product.category()
Your create() should look like this:
#api.model
def create(self, values):
categs = self.env['product.category'].search([])
values['categs'] = [(6,0,categs.ids)]
id = super(odepoContact, self).create(values)
_logger.error(id.categs)
return id
That code example is for a Many2Many field (categs), which i would prefer here. For Many2Many you need to use a List of tuples. You can find the possible tuples here.

Django Integrity Error - id cannot be null

I know this has been answered before, but I have been through every answer and nothing either makes sense or I feel like my code is already doing what is being said in the answers.
So I have a model for terms and links, which has a many-to-many relationship.
class ProjectTerms(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
terms = models.CharField(max_length=100)
class Meta:
db_table = 'project_terms'
class ProjectLinks(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
links = models.CharField(max_length=100)
relations = models.ManyToManyField(ProjectTerms)
class Meta:
db_table = 'project_links'
class ProjectLinksRelations(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
project_terms = models.ForeignKey('ProjectTerms')
project_links = models.ForeignKey(ProjectLinks)
Script:
def create_models(my_term, my_link):
saved_term = ProjectTerms.objects.update_or_create(terms = my_term)
saved_link = ProjectLinks.objects.update_or_create(links = my_link)
ProjectLinksRelations.objects.update_or_create(project_terms=saved_term, project_links=saved_link)
A lot of places say that the model (both term and link here) has to be saved before being added to the connecting database.
I've also tried creating each term and link separately and saving them like this:
def create_models(my_term, my_link):
saved_term = ProjectTerms(terms = my_term)
saved_term.save()
saved_link = ProjectLinks(links = my_link)
saved_link.save()
relation = ProjectLinksRelations.objects.update_or_create(project_terms=saved_term, project_links=saved_link)
relation.save()
All you need for this is:
class ProjectTerms(models.Model):
terms = models.CharField(max_length=100)
class ProjectLinks(models.Model):
links = models.CharField(max_length=100)
relations = models.ManyToManyField(ProjectTerms)
The ID fields and the table for the ManyToManyField will be automatically created.
To set the ManyToMany relationship, use add:
def create_models(my_term, my_link):
(saved_term, created) = ProjectTerms.objects.update_or_create(terms = my_term)
(saved_link, created) = ProjectLinks.objects.update_or_create(links = my_link)
saved_link.relations.add(saved_term)
saved_link.save()

session.add(self) not adding record to db

total novice here. Trying to work with sqlalchemy but have hit a problem.
class Establishment(Base):
__tablename__ = 'establishments'
estaID = Column(String(5), primary_key=True)
typeID = Column(String(2), ForeignKey('types.typeID'))
type = relationship("Type", backref=backref('estabs', order_by=estaID))
def __init__(self, id):
self.estaID = id
try:
session = Session()
existsEsta = session.query(Establishment).filter(Establishment.estaID == self.estaID).one()
session.close()
self.typeID = existsEsta.typeID
except NoResultFound, e:
session = Session()
print "Establishment: ", self.estaID, "does not yet exist."
type = Type(raw_input("Please enter type: "))
self.typeID = type.gettypeID()
print "Adding establishment", self.estaID, self.typeID
session.add(self)
session.commit
For some reason, the session.add(self) is not adding the record to the db. I'm having particular difficult figuring out what's going on because this "Establishment" class is modeled after another class (identical algorithm, different variable names) which works just fine.
Thoughts as to where I'm going wrong here?
Thanks in advance.
Try session.commit() instead of session.commit.

How to edit a existing record with ColanderAlchemy?

I have a SQLAlchemy model like this:
class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, primary_key = True, ca_include = True)
name = Column(String, ca_include = True)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key = True, ca_include = True)
name = Column(String, ca_include = True)
group_id = Column(Integer, ForeignKey('groups.id'), nullable = True, ca_include = True)
group = relationship('Group', ca_include = True)
The form library I used is deform. I installed ColanderAlchemy to convert the model definition into Colander Schema automatically:
form = deform.Form(SQLAlchemyMapping(Group), use_ajax = True)
And I can do form.render() to get a empty form. But how to fill this empty form with a record?
I tried:
group = Group.get(1)
form.render(group)
But failed.
I also followed this blog but it can only convert a single record into colander's format but no relationship would be converted.
So... is there anyway for me to convert the SQLAlchemy record into Colander record?
You'll need to utilise the dictify method associated with your given SQLAlchemyMapping schema object to convert a given model instance into an appstruct acceptable for rendering your Deform form.
So, using your example model, this is what you might do:
schema = SQLAlchemyMapping(Group)
form = deform.Form(schema, use_ajax=True)
my_group = Group(id=1, name='Foobar') #or query for an instance etc
appstruct = schema.dictify(my_group)
form.render(appstruct)
Since ColanderAlchemy is very much cutting edge at this stage, your mileage will likely vary in newer versions (the above was written for version 0.1), especially as it is being substantially rewritten to remove the need for custom columns and relationship types in version 0.2. I've noticed that there were issues with the the current ColanderAlchemy 0.1b6 release - especially with regards to the mapping of relationships.
Consult the documentation at http://colanderalchemy.rtfd.org/ for details on the latest version.