Nayana
Nayana

Reputation: 1549

how to add one object to queryset

oldHref = c.common.externalLinks.all()
newHref = m.common.externalLinks.all()
m.common.externalLinks = list(chain(oldHref,newHref))

This compiles and works fine.

But what I want to do is

for x in oldHref:
    if ... :
        m.common.externalLinks = list(chain(newHref, x))

This does not compile.

Just to give you an idea of their types:

m.common.externalLinks.all() =  [<List: List object>] #same as newHref
x =  List object

Upvotes: 1

Views: 4071

Answers (1)

Matthew Schinckel
Matthew Schinckel

Reputation: 35639

It's not exactly clear what you are trying to do, but I think you are trying to get the union of two querysets.

If this is the case, you can use:

c.common.externalLinks.all() | m.common.externalLinks.all()

An alternative may be to use:

ExternalLink.objects.filter(common__in=[m.common, c.common])

But that will depend on what the rest of your code looks like.

An aside on python style: try to use snake_case rather than camelCase.

Okay, it's not the union you want: perhaps you want to add all of the values from m.common.externalLinks.all() into c.common.externalLinks?

c.common.externalLinks.add(*m.common.externalLinks.all())

Or, if you only want the first one:

c.common.externalLinks.add(m.common.externalLinks.all()[0])

Upvotes: 1

Related Questions