Django self-recursive foreignkey filter query for all childs

You can always add a recursive function to your model: EDIT: Corrected according to SeomGi Han def get_all_children(self, include_self=True): r = [] if include_self: r.append(self) for c in Person.objects.filter(parent=self): _r = c.get_all_children(include_self=True) if 0 < len(_r): r.extend(_r) return r (Don’t use this if you have a lot of recursion or data …) Still recommending mptt … Read more

Find Parent Recursively using Query

Here’s a complete example. First the DDL: test=> CREATE TABLE node ( test(> id SERIAL, test(> label TEXT NOT NULL, — name of the node test(> parent_id INT, test(> PRIMARY KEY(id) test(> ); NOTICE: CREATE TABLE will create implicit sequence “node_id_seq” for serial column “node.id” NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index … Read more

SQL Server recursive query

Look into using what is called a CTE (common table expression) (Refer to MSDN document): ;with cteAppointments as ( select AppointmentID, PersonID, PrevAppointmentID from Appointments where PrevAppointmentID is null union all select a.AppointmentID, a.PersonID, a.PrevAppointmentID from Appointments a inner join cteAppointments c on a.PrevAppointmentID = c.AppointmentID ) select AppointmentID, PrevAppointmentID from cteAppointments where PersonID = … Read more

MySQL how to fill missing dates in range?

MySQL doesn’t have recursive functionality, so you’re left with using the NUMBERS table trick – Create a table that only holds incrementing numbers – easy to do using an auto_increment: DROP TABLE IF EXISTS `example`.`numbers`; CREATE TABLE `example`.`numbers` ( `id` int(10) unsigned NOT NULL auto_increment, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; Populate the table … Read more