The problem
I'm trying to create many functions in my project that let me easily create, delete and alter data using Model.objects.function(), but I have just learned that you cannot access 'manager' via instances: AttributeError: Manager isn't accessible via Address instances.
I had a function to turn the string of a model into the actual model e.g. if model == 'author: return Author so that I could use them as the inputs to other functions but this doesn't seem to work.
I can't seem to input classes into functions either, so I'm not sure how to resolve this.
Any help would be greatly appreciated.
Context
I am trying to create these functions as commands in myproj/management/commands.
Currently the code looks like this:
myproj/management/commands/insert_random_data.py
from django.core.management.base import BaseCommand, CommandError
from ._private import *
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('model', type=str)
def handle(self, *args, **options):
model = options['model']
if model == "all":
ad = format_data("address", generate_data("address"))
ra = format_data("rating", generate_data("rating"))
.
.
.
myproj/management/commands/_private.py
from myproj.models import *
import string
import random
def string_to_model(string):
string = string.lower()
if string == "author":
model = Author
elif string == "seller":
model = Seller
elif string == "address":
model = Address
elif string == "rating":
model = Rating
elif string == "product":
model = Product
elif string == "edition":
model = Edition
elif string == "tag":
model = Tag
elif string == "taglisting":
model = TagListing
elif string == "booklisting":
model = BookListing
elif string == "picture":
model = Picture
else:
return ValueError
return model
def format_data(model, d, foreignkey1=None, foreignkey2=None):
model = string_to_model(model)
if d is not None:
if foreignkey1 != None:
if foreignkey2 != None:
return model(*d, foreignkey1, foreignkey2).objects
return model(*d, foreignkey1).objects
else:
return model(*d).objects
else:
if foreignkey1 != None:
if foreignkey2 != None:
return model(foreignkey1, foreignkey2).objects
return model(foreignkey1).objects
else:
return model.objects
generate_data() just returns a list containing data to enter into the field.