I have two tables which has relationship.
class Parent(SafeDeleteModel):
name = models.CharField(max_length=1048,null=True,blank=True)
class Child(SafeDeleteModel):
name = models.CharField(max_length=1048,null=True,blank=True)
parent = models.ForeignKey(Parent,blank=True, null=True, on_delete=models.CASCADE,related_name="parent_project")
In this case I can filter the Child by Parent such as
Child.objects.filter(parent__name__contains="test")
However I want to do the reverse like this below.
Parent.objects.filter(child__name__contains="test")
Is it possible?
I tried like this below
Parent.objects.filter(parent_project__contains="test")
however this error
django.core.exceptions.FieldError: Unsupported lookup 'contains' for ManyToOneRel or join on the field not permitted.
2
You can set yourself as a foreign key through your own string.
class model(SafeDeleteModel):
name = models.CharField(max_length=1048,null=True,blank=True)
parent = models.ForeignKey(
'self',
blank=True,
null=True,
on_delete=models.CASCADE,
related_name="children"
)
# Model whose parent name is a
model.objects.filter(parent__name='a')
# Select only the parent model
model.objects.filter(parent=None)
# Model with child name b (related name set to children)
model.objects.filter(children__name='b')
# Model with c in child name (related name is set to children)
model.objects.filter(children__name__contatins='c')
1
few notes:
- your model should inherit
models.Model
- the first parameter of the ForeignKey should point to
Parent
notProject
if the relationship is between parent and child.
Then you can query using related_name:
Parent.parent_project.filter(name="child name")
1
if you want this Parent.objects.filter(child__name__contains="test")
to work just add related_query_name = child
as a parameter
helpful resources related_name and related_query_name