My django table contains a field that contains comma-separated strings.
class RawData(TimeStampModelMixin):
id = models.UUIDField(primary_key=True)
media = models.TextField()
media column will hold values like 'Multimedia, TV', 'Multimedia, TV Station'. I need to filter Rawdata table rows such that media column contains 'TV' or 'Multimedia'. __icontains doesn't provide the accurate result. If I do
Rawdata.objects.filter(media__contains='TV')
then it will return both 'Multimedia, TV', 'Multimedia, TV Station' rows. But I need only the 'Multimedia, TV' row.
Is there any way to achieve this via queryset API?
CodePudding user response:
As Hedde suggested, better create model like MediaType
and set proper relationship:
class MediaType(models.Model):
name = models.TextField()
class RawData(TimeStampModelMixin):
id = models.UUIDField(primary_key=True)
media = models.ManyToManyField(MediaType)
Then you will be sure, that seeking for a specific type(s) you will not be mistaken with some similar types.
EDIT: because of above solution is not possible for this particular situation, there is an alternative with Q
object (symbol |
means or
):
from django.db.models import Q
Rawdata.objects.filter(Q(media__contains='TV,') | Q(media__endswith='TV'))
As I understand it correctly, every situation that 'TV'
is inside media
field, it has to be in the end of the string or followed directly by a comma.
CodePudding user response:
This may not be the best answer. but seeing the exact need you have maybe can do the job with the data you have.
Rawdata.objects.filter(
media__startswith='Multimedia',
media__endswith='TV'
)