Tuesday, February 27, 2018

Re: How to get Foreign Key Objects programmatically?

Did you ever find an answer? If so, do you mind sharing it? Thanks.

On Sunday, October 29, 2017 at 9:33:10 AM UTC-7, rmschne wrote:
I'm using Django as front end to a MySQL database. User interface is a terminal program, not a web site.

I've written a very simple generic function to edit the fields of one record of a Django "object".  It works fine for editing editable fields. User specifies which field, then is shown the current value, raw_input() for the new value, then save() the record.

For fields that connect to Foreign Keys, what I want to do is present to user a simple list of Foreign Key records, from which the user will pick the relevant ID.  I know, given a list and the ID, how to then edit the record by doing a Django get(id=ID) on the Foreign Key table.  What I'm having trouble doing is figuring how

1. Identify into a variable the name of the Foreign Key table/object
2. Then with that variable do a call to the relevant Foreign Key table, e.g. ForeignKeyTable.objects.all()

See code below for <===WHAT I DO NOT KNOW HOW TO DO IN CODE Below.  I think I need some Django function that gives me the foreign key table in some useable generic form.

Hope all this makes sense. 

--rms

def EditDjangoObjectData(djangoobject,show=False,editonerecord=False):
    """
    EditDjangoObjectData()
        djangoojbect=a django object, e.g. a record in a table
    """
    print "\n****ToDo Note: This routine not yet working on fields with foreign keys!"
    changelist=[]
    ok=True
    while ok:
        change=None
        fields = [(f.name, f.editable) for f in djangoobject._meta.get_fields()]
        if show:
            print "\nfields:\n",fields
            print "django object:\n",djangoobject
        s="\nEditable Fields ('enter' to return): \n"
        fieldlist=[]
        for i in fields:
            if i[1]:   # only for 'editable' fields
                if i[0].lower() <> "id":
                    s=s+i[0]+", "
                    fieldlist.append(i[0])
        s=s+"DELETE or '?'"
        fieldok=False
        while not fieldok:
            fieldtochange=raw_input("Enter field name to change:\n"+s+": ")
            if not fieldtochange:
                return None
            elif fieldtochange.upper()=="DELETE":
                ans=raw_input("...Confirm DELETE by typing 'DELETE': ")
                try:
                    if ans=="DELETE":
                        rtn=djangoobject.delete()
                        print "Deleted. ",rtn
                        return rtn
                except:
                    print "***DELETE Failed.",sys.exc_info()[0]
                    ans=raw_input("Press 'Enter' to continue ... ")
            elif fieldtochange=="?":
                PrintObjectDetails(djangoobject)
            elif fieldtochange in fieldlist:
                fieldok=True
            else:
                print "\n****Error. ",fieldtochange,"is not in list. Try again."
        print "Current Value of Field to Change:",fieldtochange,"is:",getattr(djangoobject, fieldtochange)
**
** In here add some code to show a list of the foreign key records for user to select, e.g. ID, Description, 
**for r in ForeignKey.objects.all():   <== WHAT I DO NOT KNOW HOW TO DO IN CODE.
**    print i.id, i.description
**ID=raw_input("Enter ID:)
**foreignkeyobject=ForeignKey.objects.get(id=ID)    <== WHAT I DO NOT KNOW HOW TO DO IN CODE.
** ... then put that object into the relevant field 
        newvalue=raw_input("Enter New Value: ")
        change="changed ["+fieldtochange+"]"
        print "\nTo Save   :",djangoobject
        print "The Change:",change,"to",newvalue
        if not newvalue:
            return None
        elif newvalue.lower()=="none":
            newvalue=None
        elif newvalue.lower()=="true":
            newvalue==True
        elif newvalue.lower()=="false":
            newvalue=False
        setattr(djangoobject, fieldtochange, newvalue)
        try:
            djangoobject.save()
            print ": Success. Saved:",change,"to",newvalue
            print ": New Object:",djangoobject
            changelist.append(change)
            print "ChangeList:",changelist
        except:
            print "***Save Failed.",sys.exc_info()[0]
            ans=raw_input("Press 'Enter' to continue ... ")
        if editonerecord:
            ok=False
    return changelist

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e6ddd293-66ac-496a-94d4-10fd44cb1224%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment