lucasrf27
lucasrf27

Reputation: 360

Django create data with OnetoOneField

Hello thanks for your time:

i'm trying to add some data to my model table trough management/commands/create_data.py:

Question

besides that i guess i'm gonna recieve an error at user field on People model because should be an id. How do i get the id?

pets/models.py:


User = get_user_model()



class People(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person')
    birthday = models.DateField()
    cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')])

    def __str__(self):
        return '%s' % (self.user)

pets/management/commands/create_data.py:

User = get_user_model()


class GenerateUser():
    username = None
    password = None
    def __init__(self, username, password):
        with open('User.txt') as file:
            for rows in file:
                self.username = slugify(rows)
                self.password = '12345'


class GeneratePeople():
    user = None
    documento = None
    birthday = None
    def __init__(self, documento, birthday):
        with open('People.txt') as file:
            for rows in file:
                t1 = rows.split(', ')
                self.user = slugify(t1[0])
                self.documento = t1[1]
                self.birthday = t1[2]



class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument(
            'file_name', type=str, help='ok')

    def handle(self, *args, **kwargs):

        username = GenerateUser.username
        password = GenerateUser.password
        user = GeneratePeople.user
        documento = GeneratePeople.documento
        birthday = GeneratePeople.birthday

        one = User(
            username=username,
            password=password
            )

        one.save()

        peop = People(
            user=user,
            documento=documento,
            birthday=birthday
        )

        peop.save()


        self.stdout.write(self.style.SUCCESS('Data imported successfully'))

People.txt:

Johnny Cash,    555555555,  1932-02-26
Sid Vicious,    555555555,  1957-05-10
Axl Rose,   555555555,  1962-02-06
Joey Ramone,    555555555,  1951-05-19
Bruce Dickinson,    555555555,  1958-08-07
Kurt Cobain,    555555555,  1967-02-20
Elvis Presley,  555555555,  2008-19-17

User.txt:

Johnny Cash
Sid Vicious
Axl Rose
Joey Ramone
Bruce Dickinson
Kurt Cobain
Elvis Presley

Upvotes: 0

Views: 376

Answers (1)

Dual1ty
Dual1ty

Reputation: 188

Hi i dont have enough reputation yet to write a comment on your post but if you just want to add data to populate tables in django i would suggest using the method described here in the documentation. This way its much easier and hustle free.

https://docs.djangoproject.com/en/3.0/howto/initial-data/

In summary:

  • create a 'fixtures' directory inside your app.
  • create the datafile you want to add that match the model fields either as json or yml.
  • call manage.py loaddata datafile_name

I hope that helps. If not since you can comment let me know and i can delete this.

Upvotes: 1

Related Questions