Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert queryset results into ManytoManyfield

Tags:

django

I have a models.py file that looks like this:

from django.db import models
from common.models import Record
from tinymce import models as tinymce_models

# Create your models here.
class Address(Record):
    def __unicode__(self):
        return unicode(self.ip)

    ip = models.IPAddressField(unique=True)
    notes = models.TextField(blank=True)

    class Meta:
        verbose_name_plural = "Addresses"

class Servers(models.Model):
    def __unicode__(self):
        return unicode(self.server_name)

    server_name = models.CharField(max_length=100)
    ip_address = models.ForeignKey(Address)
    secondary_ips = models.ManyToManyField(Address, verbose_name = 'Secondary IPs', blank=True, related_name='secondary_ips')

    class Meta:
        verbose_name_plural = "Servers"

I have a list of IP's and Servers in the system. I am trying to have the ManytoManyField only display the list of IP's that are not currently associated with a server.

I have the following queryset:

inner_qs = Servers.objects.values_list('ip_address_id', flat=True)
entries = Address.objects.exclude(id__in=inner_qs)

It returns only the IP addresses that are not in the Server table. I do not know how to incorporate those results into my ManytoManyField and where I am supposed to place my queryset. I currently only get the results when I enter the django Shell

Any ideas,

Thanks

like image 693
user1607158 Avatar asked Dec 08 '22 22:12

user1607158


2 Answers

If you want to add a queryset to a many to many field first change it into a list and add it as positional arguments using *

Example

# Returns a queryset
permissions = Permission.objects.all()

# Add the results to the many to many field (notice the *)

group = MyGroup.objects.get(name='test')

group.permissions.add(*permissions)
like image 124
Dr Manhattan Avatar answered Jun 04 '23 04:06

Dr Manhattan


Returns a queryset

permissions = Permission.objects.all()

Add the results to the many to many field (notice the *)

group = MyGroup.objects.get(name='test')
group.permissions.add(*permissions)
like image 31
Anymnous Avatar answered Jun 04 '23 04:06

Anymnous