On Jul 19, 3:00 pm, rmschne <rmsc...@gmail.com> wrote:
[snip]
> The pointer you gave, thanks very much, explains how to set the data
> model to allow nulls, which I've done already.  Further, as I
> originally mentioned, I'm not using Django to control data entry, so
> the None=True in the data model doesn't really have any impact, I
> think.  Perhaps i'm wrong on that; but no matter because the data with
> null parent fields are indeed in the database.
>
> My problem, perhaps badly explained, was to extract with Django
> queryset all those records in the without parents.  That's what's
> vexing me.

Hi,

I think the query you are looking for is quite simple.

>From what I understand (correct me if I have got it wrong), your
models are something like this:

class ChildModel(models.Model):
    foo = models.CharField(max_length=20)
    parent = models.ForeignKey(Parent, null=True,
related_name="child")

class ParentModel(models.Model):
    bar = models.CharField(max_length=20)

To get children without parents, you just do:

ChildModel.objects.filter(parent__isnull=True)

The first time I read your question I was really confused (I think
because you had got so many replies that weren't answering your
question, I thought it was more complicated than it actually was), and
thought you had got your child / parent analogy the wrong way and were
actually asking how to do the query from the other side (ie actually
getting childless parents), which is a bit more complicated, but not
much, so I figured out how to do that too (if you care).

To get the childless parents you do:

childless= ParentModel.objects.filter(child__isnull=True)

Be warned though, if you want to use it to find the parents that have
children (ie aren't childless), you *don't* want to do this:

parents = ParentModel.objects.filter(child__isnull=False)  # won't
give you what you expect

because if the foreign key is not one to one, then you will get the
multiplicity for want of a better word. i.e. if you have one parent
record that is a ForeignKey from two children, then that parent will
be returned twice. To eliminate these duplicates, you should do:

parents = ParentModel.objects.filter(child__isnull=False).distinct()

Hope that helps in some way (rather than confuses),
Em

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to