Home > Enterprise >  Is there a way to make the 'One' table optional in OneToManyRelationship in Django
Is there a way to make the 'One' table optional in OneToManyRelationship in Django

Time:08-27

I have two tables, one is Anonym the other is Userdatabase. I want my app to work without requiring any login info therefore it will work with Anonym only by using the deviceid of the user to process account information. If however, a user wants to access extra features they need to create a user with username/password. Then I will process the data using Userdatabase table. A user can have multiple devices so there is a OneToMany relationship in there, but a device doesn't have to have a User (they don't need to register) which breaks the relationship. Is there a way to make the Userdatabase table optional while keeping the OneToMany relationship? Perhaps by inserting a method or another class within UserDatabase? Please find the code below:

--Models--

class Anonym(models.Model):
    deviceid=models.ForeignKey(Userdatabase,max_length=200,on_delete=models.SET_NULL,null=True)
    accounttype=models.TextField(default='Free')
    numberofattempts=models.IntegerField(default=0)
    created=models.DateField(auto_now_add=True)

class Userdatabase(models.Model):
    username=models.CharField(max_length=20,unique=True)
    password=models.CharField(max_length=20)
    deviceid=models.TextField(default='inputdeviceid')
    accounttype=models.TextField(default='Free')
    numberofattempts=models.IntegerField(default=0)
    created=models.DateField(auto_now_add=True)

--urls--

urlpatterns=[path('deviceregister/<str:id>/',views.deviceregistration)]

--views--

def deviceregistration(request,id):
    import time

    deviceid=id
    newdevice-models.Anonym(created=time.strftime("%Y-%m-%d"),deviceid=deviceid)
    newdevice.save()

    return HttpResponse('Succesful registration')

When I send a request as '/deviceregister/123456/' for example, django raises an ValueError saying Cannot assign "'123456'": "Anonym.deviceid" must be a "Userdatabase" instance.

CodePudding user response:

you should search by fieldname, which contains id. in your case it is deviceid_id.

newdevice=models.Anonym(created=time.strftime("%Y-%m-%d"),deviceid_id=deviceid)

deviceid in your case should be Userdatabase.objects.get(pk=id)

deviceid=Userdatabase.objects.get(pk=id)
newdevice=models.Anonym(created=time.strftime("%Y-%m-%d"),deviceid=deviceid)

in my opinion - field names in your project really can confuse anyone

CodePudding user response:

If you do not want to change your model, you can just link any newly-added device to a dummy user. When later a user want to link a device, replace dummy with the real user.

If you can change your model, you can remove the foreign key relationship, and add another table which links the id of both side: one field for deviceid and the other userid.

I know both options kind of smell, but at least they should work :)

  • Related