I have csv file with user addresses, and his phone number, How can i import it in my address table. Since I dont know user id of each user.
CSV FILE in xlsx:
Format of csv:
user_id__phone,address1,address2,state,country,pincode
99999999,"addrss","addres2",somestate,Country,11111
i'm getting following error
Line number: 1 - null value in column "user_id_id" of relation "proj_auth_useraddress" violates not-null constraint DETAIL: Failing row contains (432, null, null, someaddress, , , null).
But i know relationship of user and address is through his phone number. user_id__phone
# Models.py
class AppUser(AbstractUser):
phone = models.CharField(max_length=15, unique=True, null=True)
...
class UserAddress(models.Model):
address_id = models.AutoField(primary_key=True)
user_id = models.ForeignKey(AppUser, on_delete=models.CASCADE)
lat = models.FloatField(null=True, blank=True)
lng = models.FloatField(null=True, blank=True)
address1 = models.CharField(max_length=100)
address2 = models.CharField(max_length=100, null=True, blank=True)
city = models.CharField(max_length=50)
pincode = models.IntegerField()
# Admin.py
@admin.register(UserAddress)
class AddressAdmin(ImportExportModelAdmin):
resource_class = AddressAdminResource
# Resource.py
class AddressAdminResource(resources.ModelResource):
class Meta:
model = UserAddress
import_id_fields = ('address_id',)
CodePudding user response:
If phone in AppUser is unique for each user then you can use pandas to migrate records from csv to database
You can try below solutions:
import pandas as pd
csv_file = pd.read_csv(<yourcsvfile>.csv)
for index, rows in csv_file.iterrows():
user_id__phone = rows["user_id__phone"]
address1 = rows["address1"]
address2 = rows["address2"]
country = rows["country"]
pincode = rows["pincode"]
appuser_instance = AppUser.objects.get(phone=user_id__phone)
# get_or_create is used to eliminate forming or any duplicate record
usershipping, created = UserAddress.objects.get_or_create(
user_id=appuser_instance,
address1=address1,
address2=address2,
city=city,
pincode=pincode
)
# created defines whether new record was created or was edited on existing record
# created = True (new record created)
# craeted = False (edited on existing record)
if created:
usershipping.save()
