Here's what I came up with, in case someone else finds this useful.

I'm quite proud, actually.

from django.core.management.base import BaseCommand, CommandError
from hostdb.models import Device, Interface

def sanitized_value(v):
    if v == None:
        return ""
    return v

class Command(BaseCommand):
    args = '<hostname1 hostname2...>'
    help = 'Display host information for the specified host(s)'

    def handle(self, *args, **options):
        for hostname in args:
            if hostname.find('.mitre.org') == -1:
                hostname = hostname + '.mitre.org'
            try:
                dev = Interface.objects.get(fqdn=hostname).device
            except Device.DoesNotExist:
                raise CommandError('Host "%s" does not exist' % hostname)

        # pk, the object defining the primary key of our model
        pk = Device._meta.pk

        # We turn this on because we know in our case our pk is "id"
        # which is pointless to print out in this context
        skip_pk = True

        # Iterate over all field objects (ManyToMany are not included
        # in this for some reason), in the order they are defined
        # in the model (thankfully!).
        for field in Device._meta.fields:
            if (field == pk) and skip_pk: continue
            vname = field.verbose_name
            val = sanitized_value(field.value_from_object(dev))
            self.stdout.write("%s: %s\n" % (vname, val))

        # Now handle the ManyToMany fields
        for field in dev._meta.many_to_many:
            m2m_manager = getattr(dev, field.name)
            vname = field.verbose_name
            l = []
            # Using ','.join(m2m_manager.all()) doesn't work because
            # ManyRelatedManager objects are not iterable.  We have to do 
this.
            for t in m2m_manager.all():
                l.append(str(t))
            val = ','.join(l)
            self.stdout.write("%s: %s\n" % (vname, val))

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/uPCHH_GqFDcJ.
To post to this group, send email to django-users@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