Cloud Storage
Cloud Storage

Reputation: 21

What is the best way to store array of characters in django model?

I have an array of MAC addresses. How do I store them in Django 1.7 model? My code is:

MAC=models.CharField(max_length = 20,null=True,blank=True)

I have to store different MAC address for a single user

Upvotes: 2

Views: 1109

Answers (2)

Cloud Storage
Cloud Storage

Reputation: 21

The best way is to use a ManyToMany Field.

My models.py

class MacAddress(models.Model):
    address = models.CharField(max_length = 20,null=True,blank=True)
    def __unicode__(self):
        return self.address

class UserProfile(models.Model):
    user = models.OneToOneField(User,primary_key=True,db_index=True)
    MAC=models.ManyToManyField(MacAddress)
    def __unicode__(self):
        return self.user.username

views.py

mac = get_mac()
            mac = (hex(mac))
            MacAdd=MacAddress()
            MacAdd.address=mac
            MacAdd.save()
            profile.save()
            profile.MAC.add(MacAdd)
            profile.save()

Upvotes: 0

schillingt
schillingt

Reputation: 13731

It depends on your usage. I'm going to guess that you want to assign a variable number of MAC addresses to some other model and each MAC address can only be used once.

class Parent(models.Model):
    pass

class MacAddress(models.Model):
    parent = models.ForeignKey(Parent, related_name='mac_addresses')
    address = models.CharField(max_length = 20,null=True,blank=True, unique=True)

So for each address in your array, you'd create a new instance of MacAddress

Upvotes: 2

Related Questions